I am developing some flight simulator programme. Right now I am trying to get the level to restart after a delay of 4 seconds, but instead it is waiting forever and not responding. This is my 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 for x seconds");
Application.LoadLevel(Application.loadedLevel);
Debug.Log ("Reloaded level");
}
It would be a great help if anyone could find a problem in the code, because I have been trying all day and I cannot fix it.
You are destroying the gameobject that contains the script on line 20. That causes the function to stop executing. You could for example disable the mesh renderer component instead.
You could do what the past answer said, or use the meathod Invoke() under MonoBehaviour. You can invoke a method and specify a delay that Unity will wait for to Invoke the specified method.
This would require you to make a new method with the required code to execute after 4 seconds.
My guess is you are using an object that has no MeshRenderer but does have children with MeshRenderers. In this case it would probably be easier to just destroy the gameobject and make another gameObject which will load the next level, i.e. you could combine your Update and Wait like so
Where WaitClass is a class performs the rest of the Wait method, i.e.
public class WaitClass : MonoBehaviour {
public IEnumerator Wait(float TerrainHeightLocation) {
Debug.Log("Waiting");
yield return new WaitForSeconds(4.0f); // waits x seconds
Debug.Log("Waited for x seconds");
Destroy(gameObject);
Application.LoadLevel(Application.loadedLevel);
Debug.Log("Reloaded level");
}
}