- Home /
Problem with instantiating the object in untiy at certain time intervals
Hello Community I'm a complete beginner in untiy and trying to figure spawn objects randomly at fixed time intervals (every 1 or 2 seconds).. But the issue I'm facing in my script is that the random object is only spawning once and then not spawning.. Where could I be possibly wrong ?
The idea is - I'm trying to create an endless runner where I want my obstacles to get spawned randomly at any place (but near the player transform and not outside the ground).. So I decided to spawn them after every 1 or 2 seconds so I could keep up the spawning and the game pace proper. Please suggest me alternatives too if you have any .. would do a great deal of help !!! Thanks :)
How are you starting the routine? It should look something like:
void Start()
{
this.StartCoroutine(this.Example());
}
What is SpawnRandom() for? When are you calling Example()? Who calls which, and when()?
Answer by I5 · Sep 12, 2018 at 04:34 PM
My suggestion would be to use a single "master/controller" script one some empty game object (you may already be doing that), and instead of using a coroutine, I'd try using the Update method instead. The code below should get you started if you wanted to try using Update instead of a coroutine:
private float nextSpawnTime = 0f;
private List<GameObject> spawnedChars = new List<GameObject>();
private int maxCharsPlusOne = 11;
void Update() {
if (Time.time > nextSpawnTime && spawnedChars.Count < maxCharsPlusOne) {
nextSpawnTime = Time.time + UnityEngine.Random.Range(1f, 2f);
spawnRandom();
}
}
void spawnRandom() {
spawnedChars.Add(Instantiate("insert your params for instaniating"));
}
Thanks a lot I5 ! Would surely try and get back to you !
Your answer
![](https://koobas.hobune.stream/wayback/20220612174457im_/https://answers.unity.com/themes/thub/images/avi.jpg)