- Home /
Problem: Random Instantiating more than one prefab?
Hello Everyone, i'm pretty new at coding, and I would like to spawn a prefab every X second (the time is set from the inspector). The script works fine, but I really can't understand why, once in a while, it instantiates two overlapping prefabs, and not just one. Any idea? :)
Thanks to everyone :)
using UnityEngine;
using System.Collections;
public class Game_manager : MonoBehaviour {
public Transform[] teleport;
public GameObject[] prefab_tele;
public float waitTime;
bool spawning = false ; // are we spawning?
IEnumerator SpawnPics() {
spawning = true ; //going to spawn now
int tele_num = Random.Range(0,teleport.Length);
int prefab_num = Random.Range(0,prefab_tele.Length);
Instantiate(prefab_tele[prefab_num], teleport[tele_num].position, teleport[tele_num].rotation );
yield return new WaitForSeconds(waitTime);
spawning = false ; //done spawning
}
void Update(){
if(!spawning)
StartCoroutine(SpawnPics()) ;
}
}
Answer by Patel-Sagar · Apr 08, 2014 at 09:59 AM
well I tried your code. there seems no problem here. may be other script affecting your scene. you can try in another scene with only this script enabled.
If the problem still remain, you can try InvokeRepeating method of unity. for that just make one method with Instantiate Line, and then call it from start via Invoke repeat. It will look way nicer and less complex.
I tried to solve it with InvokeRepeating. It seems to work! thanks!
well If tit satisfy your requirement, make it correct answer. so others can use this if they stuck at same place.
Your answer
Follow this Question
Related Questions
Spawn various enemies at random 1 Answer
How to add components to all spawned prefabs ? 0 Answers
Prefabs won't change? 1 Answer