I've put in a time delay of 10 seconds but it doesn't seem to work properly.
Delay works but you are still Instantiating the cubes inside Update. If you want to instantiate a Cube every 10 seconds you cand do the following:
IEnumerator DelayCreateCube(float delay){
while(true)
{
yield return new WaitForSeconds(10);
Instantiate(myCube, spawnLocation, Quaternion.identity);
}
}
public void Start()
{
StartCoroutine(DelayCreateCube());
}
Coroutines are executed by the engine at every frame (well, it depends on the coroutine) generally (at least in your case) immediately after all the Update
methods of all GameObjects
have been called.
When you use StartCoroutine
, it simply schedules the coroutine to be executed later, so it doesn't block the execution of Update
method:
StartCoroutine(Delay());
Destroy(myCube, 5);
CreateCube();
in the code above Delay
will be executed only after Update method has returned, so you were not actually delaying the execution of Destroy
and CreateCube
methods.
For a more detailed description of coroutines, have a look at this article.
EDIT
Just an additional consideration. I don't know exactly what you are trying to do, but it seems that you want to create and destroy a primitive at always the same location. If you haven't a good reason to do that, you can simply enable/disable
the object instead of creating a new one and destroy it again (for performances).