GC1983
September 7, 2012, 8:19am
1
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
Cripple
September 7, 2012, 8:22am
2
You have to create a Corountine in C# for this.
Replace RollBombs() with StartCoroutine(RollBombs());
More information here : Unity - Scripting API: MonoBehaviour.StartCoroutine
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?
Psymon
September 7, 2012, 11:09am
3
You need to call RollBombs in a coroutine.
StartCoroutine(RollBombs());
Ahh derp. I even tried that, but I didnt add the () for the function reference. Thank you!
– GC1983But Im having another issue with this script. The AddForce call isnt working. The whole script responds, but that line.
– GC1983You need a while() instead of an if in your coroutine.
– CrippleWhat does that have to do with the AddForce not working?
– GC1983