c# - Unity - WaitForSeconds() does not work -
i developing flight simulator programme. right trying level restart after delay of 4 seconds, instead waiting forever , not responding. code (in c#) right now:
void update () { //other irrelevant code in front float terrainheightlocation = terrain.activeterrain.sampleheight (transform.position); if (terrainheightlocation > transform.position.y) { //the plane crashed startcoroutine(wait(terrainheightlocation)); } } ienumerator wait( float terrainheightlocation) { transform.position = new vector3 (transform.position.x, terrainheightlocation, transform.position.z); instantiate(explosion, transform.position, transform.rotation); destroy(gameobject); debug.log ("waiting"); yield return new waitforseconds(4.0f); // waits x seconds debug.log ("waited x seconds"); application.loadlevel(application.loadedlevel); debug.log ("reloaded level"); }
it great if find problem in code, because have been trying day , cannot fix it.
thanks!
typically when waitforseconds doesn't work it's 1 of 2 things:
- time.timescale set 0.
- the object being destroyed before time up.
in case destroying game object runs coroutine before call yield waitforseconds. destroy deferred until end of frame code until yield execute, gameobject & monobehaviour destroyed , coroutine along it.
solution: use coroutine on object persists between level ending , restarting. make object persist when level loaded (as doing in code) need call dontdestroyonload.