# Why is Instantiate spawning too many clones?

just at a bit of an impasse with this one if anyone can help.

I am developing an endless runner, and I am trying to instantiate my obstacle prefabs by having my player go through a trigger which activates an instantiation. The problem I'm having is that when the player goes through the trigger, my code seems to instantiate multiple prefabs at a time. I'll post screenshots and my code to illustrate this better.

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

public class ObsGenerator : MonoBehaviour
{

public GameObject spawnTrigger;
public GameObject Player;
[SerializeField] private List<Transform> obstacleList;

public Transform spawnLocation;

public void OnTriggerEnter2D(Collider2D Player)
{
if (Player.CompareTag("Respawn"))
{
// for (int i = 0; i < obstacleList.Count; i++)
{
spawnObstacle();

}
}
}

public void spawnObstacle()
{
for (int i = 0; i < obstacleList.Count; i++)

if (obstacleList.Count > 0)
{
Transform chosenLevelPart = obstacleList[Random.Range(0, obstacleList.Count)];
Instantiate(chosenLevelPart);
}
}
}


Really appreciate anybody's help!

When you enter the trigger and spawn the obstacle you then were looping through and spawning once for every item in the obstacle list

public void OnTriggerEnter2D(Collider2D Player)
{
if (Player.CompareTag("Respawn"))
{
spawnObstacle();
}
}

public void spawnObstacle()
{
if (obstacleList.Count > 0)
{
Transform chosenLevelPart = obstacleList[Random.Range(0, obstacleList.Count)];
Instantiate(chosenLevelPart);
}
}
}

• That’s solved it, looking back I have no idea why I put that for loop in, but I’ve removed it and it’s working perfectly now. Thanks for your comment! – C-delb Dec 9 '19 at 16:53