- Home /
Instantiate at Intervals
Hey guys,
I need to instantiate a prefab at a given time interval. I have tried at least 20 different ways, and not one single solution I've found anywhere on the internet has worked. Here's what happens: a prefab gets successfully instantiated after waiting 2 seconds, but then it gets instantiated again every single frame, giving me tons and tons of them. Not what I need. This result has been the same for every method - using a coroutine, using invoke repeating...you name it, I've tried it.
I'm using C#. Any help is greatly appreciated.
Thank you!
Show the code you have for InvokeRepeating, that seems like a good candidate
I've removed it by now, but what I had was something like this:
void Update () {
InvokeRepeating("CreatePrefab", 2.0f, 2.0f);
}
void CreatePrefab() {
Instantiate(prefab, spawn.position, Quaternion.identity);
}
This successfully waits 2 seconds, but then instantiates on prefab per frame it seems.
I'm also trying something like this:
void Update () {
StartCoroutine("CreatePrefab");
}
IEnumerator CreatePrefab() {
Instantiate(prefab, spawn.position, Quaternion.identity);
yield return new WaitForSeconds(5.0f); //
}
but it returns the same result.
Answer by Wobbegong · Feb 12, 2014 at 03:36 AM
private float InstantiationTimer = 2f;
void Update () {
CreatePrefab();
}
void CreatePrefab()
{
InstantiationTimer -= Time.deltaTime;
if (InstantiationTimer <= 0)
{
Instantiate(prefab, spawn.position, Quaternion.identity);
InstantiationTimer = 2f;
}
}
You could change the 2f to a variable for easier control of the wait time if desired.
That works well! If I change the 2f to a variable, this essentially has the same functionality as InvokeRepeating() in that the InstantiationTimer float is the start delay and the variable would be the delay in between instantiations. Works great.
Answer by Ashish Dwivedi · Feb 12, 2014 at 03:37 AM
You are calling "InvokeRepeating" in update that's why it is happening. You need to call "InvokeRepeating" only once and that will work according to you what you are saying. Read Invoke repeating reference carefully. Call it into Start.
Thank you for your answer, Ashish. Your solution did work as you described; however, I am looking to call the function sometime other than start.
Not an issue. Simply make a public method suppose "StartInstantiation" and call your "Invokerepeating" from it. Now you need to call only this "StartInstantiation" method where ever you want whether from same same script or from another script, means on any event like mouse , button or collision, trigger etc.... Please remember to accept the answer if you think it solved your problem.