I am programming a 2D platformer where my main sprite jumps on randomly spawned bubbles/balloons. Below is the code I used. However, no balloons get generated at all but my other features in the game perfectly fine.
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);
}
}
The only error I get is: Press here to view This is what I have in the inspector: The inspector As a beginner in game development and in C# I would appreciate any help.
The error is pretty straightforward.
Your balloons array contains 2 items, thus it has items in index 0 and index 1.
randBalloon = Random.Range (0, 5);
Generates a random number, ranging from 0 to 4 (the second parameter is an exclusive int).
So, your spawner will regulary try to access index 2, 3 and 4 which are all indices that do not exist and therefore results in an index out of range exception.
You can easilly fix it by using this:
randBalloon = Random.Range (0, balloons.Length - 1);
balloons.Length will return an int of 2 in your case, because it gives you the length of your array. Since you need 0 to reference the first item of an array and not 1, we add the "-1". This way, you can never get an index out of range exception.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.