Random spawn array?

Hi, I’m trying to make upgrade crates spawn randomly over time and with the following script it works, but only for one type of crate.

I’ve made 10 different types of crates and I’d like for them al to spawn randomly, one at a time. Here’s my code:

    public GameObject crate;

    public int xPos;

    public int zPos;

    public int crateCount;

    //public int numSelectors = 10;
    //public GameObject[] selectorArr;
    //public GameObject selector;


    void Start () {

        StartCoroutine(CrateDrop());
        //selectorArr = new GameObject[numSelectors];
        //for (int i = 0; i < numSelectors; i++)
        //{
        //    /*GameObject go = */Instantiate(selector, new Vector3(xPos, 26, zPos), Quaternion.identity);

        //    //selectorArr[i] = go;
        //}
    }
    IEnumerator CrateDrop()
    {
        while (crateCount < 10)
        {
            xPos = Random.Range(10, 490);
            zPos = Random.Range(10, 490);
            Instantiate(crate, new Vector3(xPos, 26, zPos), Quaternion.identity);
           
            yield return new WaitForSeconds(3);
            crateCount += 1;


        }

    }
}

I’ve commented out what I’ve tried, but I can’t get it to work. Can anyone tell me how to make this script spawn an array of 10 types of crates randomly every 3 seconds?

add a

public List<GameObject> cratePrefabs;

to your class.

Then, when you want to spawn, change the instantiate line to

int myRandomCrate = Random.Range(0, cratePrefabs.Count);
Instantiate(cratePrefabs[myRandomCrate], new Vector3(xPos, 26, zPos), Quaternion.identity);

and you should be all set. Add the crate prefabs in Editor, and the script automatically adjusts to the number of prefabs in your prefabs Array.

1 Like

… wait. Above code spawns one random crate every 3 seconds. Here’s the code that spawns one crate each every 3 seconds:

add the List as above to the class, then Change the instantiate to

foreach (GameObject prefab in cratePrefabs){
   xPos = Random.Range(10, 490);
   zPos = Random.Range(10, 490);
   Instantiate(prefab, new Vector3(xPos, 26, zPos), Quaternion.identity);
}
1 Like

Hi csofranz. Thank you so much and sorry for the late reply! It works brilliantly