Yield WaitForSeconds doesn't work, give syntax error

Hi,

I am at a bit of an impasse. I have tried everything, but it would seem my Yield WaitForSeconds is not properly formatted, even though I have followed numerous examples. The MonoDevelop and Unity is telling me that there should not be a ( at the WaitForSeconds line. Could someone please let me know what I am doing wrong? Here is my code (I commented out what I had previously tried with creating a coroutine and then waiting a second but the load level did not get called):

	void OnTriggerEnter(Collider otherObject){
		if(otherObject.tag == "enemy"){
			Enemy enemy = (Enemy) otherObject.gameObject.GetComponent("Enemy");
			Instantiate(ExplosionPrefab, enemy.transform.position, enemy.transform.rotation);
			enemy.SetPositionAndSpeed();
			Destroy(gameObject);
			Player.Score += 100;
			
			if(Player.Score >= 1000){
				Debug.Log ("In 1000");
				yield WaitForSeconds(1f);
				Application.LoadLevel(3);
				//StartCoroutine(WinScreen ());
			}
		}
	}
	
	IEnumerator WinScreen(){
		yield return new WaitForSeconds(1);
		Application.LoadLevel(3);
		Debug.Log ("In coroutine");
	}

1 Answer

1

You can’t use a yield outside of a IEnumerator.

So what you had originally with the StartCoroutine was correct, the reason it did not run, is you destroyed the gameObject. So nothing below that would work.

Here is a fixed way of doing it.

void OnTriggerEnter(Collider otherObject){
       if(otherObject.tag == "enemy"){
         Enemy enemy = (Enemy) otherObject.gameObject.GetComponent("Enemy");
         Instantiate(ExplosionPrefab, enemy.transform.position, enemy.transform.rotation);
         enemy.SetPositionAndSpeed();
         Player.Score += 100;
 
         if(Player.Score >= 1000){
          Debug.Log ("In 1000");
          StartCoroutine(WinScreen ());
         }
		 else {
		   Destroy(gameObject);
		 }
       }
    }
 
    IEnumerator WinScreen(){
       yield return new WaitForSeconds(1f);
       Application.LoadLevel(3);
	   Destroy(gameObject);
       Debug.Log ("In coroutine");
    }

EDIT: Sorry, you were right, just not in this place. I destroy the object when it exits the frame and since in this instance it keeps going it still got destroyed before the coroutine was finished. Thanks a lot!

–

Are you destroying the gameObject anywhere else? IEnumerator WinScreen(){ Debug.Log ("In coroutine"); yield return new WaitForSeconds(1f); Debug.Log("WaitForSeconds finished, Loading Level"); Application.LoadLevel(3); Destroy(gameObject); } See if it prints them two lines.

–

@Breakend no problem :)

–