- Home /
Instantiate a single gameobject at every nth second of a minute for a total of x number of gameobjects
I want to instantiate a single gameobject every 6th second, generating a total of 5 gameobjects per minute. The seconds and minutes are referred from another script called "controller". This is the code i have, but instead of a single object, each time numerous gameobjects are generated. I don't know what is wrong with the script, any pointers would be highly appreciated! Thanks
public int count=5;
public int timeinterval=6
Void Update(){
firstmin();
}
void firstmin(){
for (int i = 0; i < count; i++) {
if (Controller.minutes==1 && Controller.seconds!=0 && Controller.seconds % timeinterval == 0) {
Vector3 pos = new Vector3 (this.transform.position.x, this.transform.position.y,
this.transform.position.z);
GameObject starinstance;
starinstance = Instantiate (star, pos, star.transform.rotation);
}
}
}
Answer by wizbit · Jul 25, 2017 at 03:54 PM
or, use a "CoRoutine", simple enough to create
:)
Coroutines have an overhead (performance cost), and are generally advised against for newcomers who could cause problems firing off too many of them.
I recommend using a timer like above so that the OP gains an understanding of how the update cycle works, before moving onto IEnumerable types.
Answer by Daemonhahn · Jul 25, 2017 at 03:45 PM
you chould just do (this is off the top of my head so may contain a couple of syntax errors but the algorithm will be correct).
int timer = 0;
int totalObjectCount = 0;
void Update()
{
if(totalObjectCount > objectLimit)
{
return;
}
timer += Time.deltaTime;
if(timer >= 6f)
{
// Instantiate object here
// set timer to 0 to start countdown again
timer = 0f;
totalObjectCount++;
}
}
This will create an object every six seconds.
You set an int called timer which acts as the timer.
You set an int called objectLimit (or just put the number directly) to set when to stop adding objects
No problem, if your problem is resolved if you could select my answer as the correct one I would really appreciate it :)
In fact you need to move the total object count part above so its like this:
int timer = 0;
int totalObjectCount = 0;
void Update()
{
if(totalObjectCount > objectLimit)
{
return;
}
timer += Time.deltaTime;
if(timer >= 6f)
{
// Instantiate object here
// set timer to 0 to start countdown again
timer = 0f;
totalObjectCount++;
}
}