- Home /
WaitForSeconds/Yield problem
Hello, Can somebody tell me what im doing wrong with this script, im clueless and can not get this WaitForSeconds to work. I want it to wait 3 seconds before it goes back to my main menu, the error at the moment says: The name 'yield' does not exist in the current context. this is the script
using UnityEngine;
using System.Collections;
public class endRace : MonoBehaviour {
private startRace race;
public GameObject GameOver;
public float WaitForSeconds;
// Use this for initialization
void Start () {
race = FindObjectOfType(typeof(startRace)) as startRace;
}
// Update is called once per frame
void Update () {
}
void OnTriggerEnter(Collider raceTrig)
{
//Stops timer and ends race
if(raceTrig.gameObject.tag == "Player")
{
race.raceStarted = false;
GameObject.Instantiate(GameOver);
yield.WaitForSeconds(3); //wait 3 seconds
Application.LoadLevel("mainmenu"); //then return to main menu
}
}
}
Answer by nventimiglia · Jul 04, 2012 at 12:39 PM
Please format your code. Your lucky I could read it.
Use a Coroutine. http://docs.unity3d.com/Documentation/ScriptReference/Coroutine.html
void OnTriggerEnter(Collider raceTrig){
StartCoroutine(StopRace());
}
IEnumerator StopRace(){
race.hasStarted = false;
GameObject.Instantiate(GameOver);
yield return new WaitForSeconds(3);
Application.LoadLevel("mainMenu");
}
Correct. In C#, as opposed to US/JS, you cannot simply put yield statements into normal functions. You need to do it the way @nventimiglia describes (also the way he deals with "WaitForSeconds").
It is really incredible to be trying to $$anonymous$$ch a beginner programmer how to use these (do not even mention the US/c# duality).
it is, really, impossible someone could really understand WHAT IS GOING ON inside such system-level program$$anonymous$$g when they are still just getting going with "understanding the syntax of the simplest commands".
It's not really about system-level program$$anonymous$$g, both are perfectly valid methods for specific tasks, and except for the more complicated syntax in C# (which is irrelevant since 99% of all Unity beginners use JS), they are both comparable. Except that Invoke() cannot be controlled on a frame-by-frame basis, and the time given is therefore only a rough estimate, and cannot be relied upon 100% (especially when using multiple calls or short intervals). Also, each call to Invoke will create an instance of a Coroutine internally, while you can put many yields into a single Coroutine.
If you need to do one specific thing at one specific point in time, use Invoke. If you want to create a sequence of logically connected tasks, use Coroutines.
Your answer
Follow this Question
Related Questions
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
C# WaitForSeconds doesn't seem to work ?? 2 Answers
Distribute terrain in zones 3 Answers
Waiting twice inside coroutine (C#) 2 Answers
Another question about yield, WaitForSeconds in c# 2 Answers