Why my Array doesnt work correctly?

“IndexOutOfRangeException: Index was outside the bounds of the array.
Spawner.SpawnTraps () (at Assets/Skrypty/Spawner.cs:19)
Spawner.Start () (at Assets/Skrypty/Spawner.cs:13)”

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Spawner : MonoBehaviour
{
    int not; //number of trap 
    public GameObject[] traps; //trap array
    public Vector3 position = new Vector3();

    private void Start()
    {
        SpawnTraps();
    }
    void SpawnTraps()
    {
        not = Random.Range(0, traps.Length - 1);
         GameObject trapsPrefab = traps[not];
        Instantiate(trapsPrefab, position, transform.rotation);
    }

}

You are not initializing the traps array in the code here. Are you giving it a size in the editor and placing the trap game objects inside??


If you Debug.Log(traps.Length);, what does it return?

You pass the wrong upper bound to Random.Range. The upper bound is exclusive for integer values. However the only case where you can get an index out of bounds exception with your code is when your array is empty.

Even with just a single element in the array you would be calling Random.Range(0, 0). As you can read in the documentation if min == max it will always return min. So 0 would be returned which is the only valid index if you have one element. However If there’s no element at all even 0 is not a valid index since there is no valid index at all.

Are you sure you actually populated the traps array? If you have several instances of that class in your scene, try adding this at the top of your “SpawnTraps” method:

void SpawnTraps()
{
    if (traps == null || traps.Length == 0)
        Debug.LogWarning("The traps array hasn't been assigned in the inspector", gameObject);

Note the second parameter to the LogWarning call. It’s a context object. If you see this warning in the console, pause your game and just single click on the log message in the console. This will highlight the context object in the hierarchy / project panel which makes it easier to figure out which object doesn’t have any traps assigned. Don’t forget to stop playmode once you identified the issue since changes to the scene during playmode are not persistant.