簡體   English   中英

Unity 2017-氣球生成器不起作用?

[英]Unity 2017 - Balloon spawner does not work?

我正在編寫一個2D平台游戲,我的主精靈會跳到隨機生成的氣泡/氣球上。 下面是我使用的代碼。 但是,除了我在游戲中的其他功能外,根本不會產生氣球。

public class spawner2 : MonoBehaviour {

public GameObject[] balloons;
public Vector3 spawnValues;
public float spawnWait;
public float spawnMostWait;
public float spawnLeastWait;
public int startWait;
public bool stop;

int randBalloon;

// Use this for initialization
void Start () {
    StartCoroutine (waitSpawner ());
}

// Update is called once per frame
void Update () {
    spawnWait = Random.Range (spawnLeastWait, spawnMostWait);   
}

IEnumerator waitSpawner()
{
    yield return new WaitForSeconds (startWait);
    while (true) 
    {
        randBalloon = Random.Range (0, 5);
        //float randY = Random.Range(-0.25f,-2.25f);
        Vector3 spawnPosition = new Vector3 (Random.Range(-spawnValues.x, spawnValues.x),Random.Range(-spawnValues.y, spawnValues.y),1);
        Instantiate ((balloons[randBalloon]),spawnPosition + transform.TransformPoint (0,0,0),gameObject.transform.rotation);
        yield return new WaitForSeconds (spawnWait);

    }
}

我得到的唯一錯誤是: 按此查看檢查器中的內容: 檢查器作為游戲開發和C#的初學者,我將感謝您的幫助。

該錯誤非常簡單。

您的Balloons數組包含2個項目,因此它的索引為0和索引為1。

randBalloon = Random.Range (0, 5);

生成一個隨機數,范圍從0到4(第二個參數是一個獨占int)。

因此,您的生成器將定期嘗試訪問索引2、3和4,它們都是不存在的索引,因此會導致索引超出范圍異常。

您可以使用以下方法輕松修復它:

randBalloon = Random.Range (0, balloons.Length - 1);

Balloons.Length在您的情況下將返回一個2的int值,因為它為您提供數組的長度。 由於您需要0而不是1來引用數組的第一項,因此我們添加“ -1”。 這樣,您將永遠無法獲得索引超出范圍的異常。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM