I have a GameObject called walkways and it’s giving me an “Array index is out of range” error code despite the fact that I have the call maximum as “walkways.Length.”
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class spawnwalkway : MonoBehaviour {
public GameObject[] walkways;
public int plat_num_random;
// Use this for initialization
void Start () {
StartCoroutine(spawnBlock());
}
// Update is called once per frame
void Update () {
}
IEnumerator spawnBlock()
{
walkways = GameObject.FindGameObjectsWithTag("walkway");
for (int z = 1; z < 100; z++)
{
Instantiate(walkways[Random.Range(0,walkways.Length)], new Vector3(-1.42637f, -0.4771186f, 2 * z + 8.574288f), Quaternion.identity);
yield return new WaitForSeconds(0.5f);
}
}
}
@DatTardisDoh
I think that was the problem.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class spawnwalkway : MonoBehaviour
{
public GameObject[] walkways;
public int plat_num_random;
// Use this for initialization
void Start()
{
StartCoroutine(spawnBlock());
}
IEnumerator spawnBlock()
{
walkways = GameObject.FindGameObjectsWithTag("walkway");
for (int z = 1; z < 100; z++)
{
//Changed from walkways[Random.Range(0, walkways.Length)]
//to walkways[Random.Range(0, walkways.Length - 1)]
Instantiate(walkways[Random.Range(0, walkways.Length - 1)], new Vector3(-1.42637f, -0.4771186f, 2 * z + 8.574288f), Quaternion.identity);
yield return new WaitForSeconds(0.5f);
}
}
}
Even though you use walkways.Length
when calling Random.Range
, there is a case you haven’t handled: What if walkways
does not contain any element? Then, Random.Range
would return 0. However, walkways[0]
does not exist since the array is empty.
So, make sure walkways
has element before calling your function.
walkways = GameObject.FindGameObjectsWithTag("walkway");
if( walkways.Length > 0 )
{
for (int z = 1; z < 100; z++)
{
Instantiate(walkways[Random.Range(0, walkways.Length)], new Vector3(-1.42637f, -0.4771186f, 2 * z + 8.574288f), Quaternion.identity);
yield return new WaitForSeconds(0.5f);
}
}
else
Debug.LogError("No walkway found! Are you sure the objects are correctly tagged?");