Random array with prefabs?
Hi I have 5 prefabs and i want to spawn them one by one randomly every 3 seconds. It doesn't matter if 2 prefabs of the same kind are spawn one after the otger, on the opposite i would like them to be able to get repeated. I managed to make 1 prefab spawn every 3 seconds but the moment i try to get the program to choose a random prefab to spawn every iteration it says that " NullReferenceException: Object reference not set to an instance of an object RandomColumnPool.Update () (at Assets/Assets/RandomColumnPool.cs:52)" and it wont even spawn one? I´m trying this:
public int columnPoolSize = 5;
public GameObject[] prefab;
void Start()
{
prefab = GameObject.FindGameObjectsWithTag("column");
for (int i=0; i< columnPoolSize; i++)
{
index = Random.Range(0, prefab.Length);
columns[i] = (GameObject)Instantiate(prefab[index], objectPoolPosition, Quaternion.identity); //for each column it instantiates its position
}
}
Sorry in advance if the question is dumb this is my first game.
Thanks!
You need to post more of your code, as the NullReferenceException happened in Update(), which is outside the code snippet you posted.
Answer by Galactic_CakeYT · Jun 12, 2020 at 02:42 PM
First, I assume that you have already created the IEnumarator already to spawn every 3 seconds. Also next time search your question, because this question is already answered, you do courses, and they ask you to solve questions like this (C# survival guide). But anyways I found something that can help you. https://answers.unity.com/questions/566508/need-to-spawn-a-gameobject-from-an-array.html
probably can help you. If you are having problems such as this, revisit the problem, break it down, and think about what it means, this is a good way to learn in the beginning.
Answer by Owen-Reynolds · Jun 12, 2020 at 11:03 PM
Try breaking it into more lines:
Debug.Log("In spawn loop, i="+i);
index = Random.Range(0, prefab.Length);
GameObject spawnMe = prefab[index];
GameObject spawnedItem = Instantiate(spawnMe, objectPoolPosition, Quaternion.identity);
columns[i] = spawnMe;
My guess is you might see an error on the last line because you didn't create enough columns.