Yield Return New WaitForSeconds() Does Not Work

Hey all,

So Ive been converting scripts from JS to C#. Ive noticed that if I have a WaitForSeconds() from the JS and try to use it in the C# converted copy, it doesnt do ANYTHING.

if(Input.GetKeyDown("x"))
{	
	//instantiate and roll bomb
	RollBombs();
}

public IEnumerator RollBombs()
	{	
		if(bombsActive)
		{	
			bombsOut++;	
			bombsEach = false;

			if(bombsOut <= 3)
			{			
				rollIsPlaying = true;	
				yield return new WaitForSeconds(player.animation["roll_bomb"].length / 3); 
				rollIsPlaying = false; 
				
			 	Instantiate(bomb, player.transform.position + player.transform.forward * .5f, player.transform.rotation);
				bomb.rigidbody.AddForce(bomb.transform.forward * 10, ForceMode.Impulse);
			}
		}	
	}

I dont get any errors before or after the execution. It just doesnt execute. Something Im missing?

3 Answers

3

You have to create a Corountine in C# for this.

Replace RollBombs() with StartCoroutine(RollBombs());

More information here : Unity - Scripting API: MonoBehaviour.StartCoroutine

Ahh derp. I even tried that, but I didnt add the () for the function reference. Thank you!

But Im having another issue with this script. The AddForce call isnt working. The whole script responds, but that line.

You need a while() instead of an if in your coroutine.

What does that have to do with the AddForce not working?

Just i would like to understand the case,because i had the same issue while calling this function

`IEnumerator OpenLevel(string levelToLoad){
	yield return new WaitForSeconds(0.35f);
	Application.LoadLevel(levelToLoad);		
}`

when i used
OpenLevel(“mylevel”) it didn’t work but when i used

and StartCoroutine(OpenLevel(“mylevel”)) it worked

but when i used it in another script inside OnMouseUp() function the yield return worked without any extra work

`IEnumerator OnMouseUp()
{
	yield return new WaitForSeconds(0.35f);
	Application.LoadLevel(levelToLoad);		
}`

any idea why?

You need to call RollBombs in a coroutine.

StartCoroutine(RollBombs());

pretty late, but thanks.

My answer needed to be confirm by a moderator that's why it was pretty late x)