- Home /
Spawn an object to a random spawn point from a list
I want to spawn 3 of the same game object at a random spawn point that I put into a list. But everytime I run my project there's an error saying ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index
I was wandering how does this error is happening, or there can be a better way to do what i am trying to implement?
private void Start()
{
foreach (GameObject obj in GameObject.FindGameObjectsWithTag("Savee"))
{
saveePoints.Add(obj);
}
spawn();
}
void spawn()
{
for (int i = 0; i <= 2; i++)
{
i = Random.Range(0, saveePoints.Count);
saveePoints[i] = Instantiate(saveeObject, saveePoints[i].transform.position, transform.rotation) as GameObject;
}
}
Answer by Metais · Jun 04, 2019 at 01:57 PM
You are changing the value of i
inside your for loop, which you are already using to cycle through it three times. Change the i
to j
or similar, perhaps that helps?
Answer by SirPaddow · Jun 04, 2019 at 02:03 PM
You shouldn't use i to count your instances and to get a random spawn position. Try something like this.
void spawn()
{
for (int i = 0; i <= 2; i++)
{
int spawnIndex = Random.Range(0, saveePoints.Count);
Instantiate(saveeObject, saveePoints[spawnIndex].transform.position, transform.rotation);
}
}
If the error is still showing after, make sure your Start function actually finds the spawn positions.
Also, I don't understand why you replace your spawn positions with your new instances... Can you tell what you are trying to do exactly?
Thanks for your feedback I still got the error but as you say my start function is not founding my spawn points I noticed it by puting a Debug.Log inside the foreach loop. What should I do? $$anonymous$$aybe it is because my spawn points were also instantiated when the game starts.
You could try to instantiate the list of save points as a new, empty list before adding new objects to it, that way you are certain of the size of the list and can understand your indexoutofbounds exception better.
Like this:
private void Start()
{
saveePoints = new List<GameObject>();
foreach (GameObject obj in GameObject.FindGameObjectsWithTag("Savee"))
{
saveePoints.Add(obj);
}
spawn();
}
Does your scene actually contain gameobjects with the tag "Savee"? I can't see why the find function would fail, but you can try to avoid it by assigning your spawn positions through the inspector by making "saveePoints" public.
Your answer
![](https://koobas.hobune.stream/wayback/20220612202618im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
A node in a childnode? 1 Answer
Affect every object in array. 1 Answer
Creating text at the position of the gameobjects in world 0 Answers
Random instantiation endlessly? 1 Answer
Problem not remove all prefab from list aftre the instantiate 1 Answer