- Home /
Script load level after few seconds, doesn't work.
Can someone explain me why this script does not work?
void OnCollisionEnter(Collision collision){
Destroy (gameObject);
WaitForSecond();
}
IEnumerator WaitForSecond(){
yield return new WaitForSeconds(2.0F);
Application.LoadLevel("Menu");
}
I want that the gameobject is destroyed when colliding and load a new level after 2 seconds.
Answer by whydoidoit · Jun 24, 2012 at 10:00 PM
In C# you have to explicitly start coroutines:
void OnCollisionEnter(Collision collision){
foreach(var r in GetComponentsInChildren<Renderer>()) //Don't destroy the object yet but make it invisible
r.enabled = false;
StartCoroutine(WaitForSecond());
}
EDIT per @Bunny83's comment below
That doesn't work since the coroutine have to run on a $$anonymous$$onoBehaviour instance. The coroutine will be destroyed when the owning gameobject is destroyed the next frame.
Yes, that's a good workaround, but i guess it's better to disable all components (or all Behaviours to be more precise). As far as i remember coroutines can still run, even when the script is disabled, but I'm not entirely sure.
foreach(var r in GetComponentsInChildren<Behaviour>())
Yeah I started down that track, then couldn't remember either :)
Answer by Bunny83 · Jun 24, 2012 at 10:19 PM
whydoidoit is right that you have to explicitly start the coroutine, otherwise it doesn't run at all. However there's another problem. When you start a coroutine, it runs on the MonoBehaviour that starts the coroutine. StartCoroutine is a member function of MonoBehaviour. You need another independent MonoBehaviour that isn't going to be destroyed next frame.
Usually you would use some kind of game manager script that can handle such cases. For your case you can simple create a seperate script that loads the level:
// LoadLevelDelayed.cs
using UnityEngine;
public class LoadLevelDelayed : MonoBehaviour
{
public float Delay = 2.0f;
public string Level = "";
IEnumerator Start()
{
yield return new WaitForSeconds(Delay);
Application.LoadLevel(Level);
}
public static void Load(string aLevel, float aDelay)
{
LoadLevelDelayed loadLevelScript = (new GameObject()).AddComponent<LoadLevelDelayed >();
loadLevelScript.Level = aLevel;
loadLevelScript.Delay = aDelay;
}
}
When you execute the static Load function it creates a new gameobject and attaches the LoadLevelDelayed script to it which will actually perform the level load
void OnCollisionEnter(Collision collision)
{
Destroy (gameObject);
LoadLevelDelayed.Load("Menu", 2.0f);
}
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
How would I have a script either wait on a timer OR for a button press? 2 Answers
cant loadlevel on C# 1 Answer
C# yield waitforseconds 3 Answers