yield waitforseconds

hi can someone please elaborate im trying to get better with csharp as i normally use java and want to be able to use both.

but cant seem to find a good explanination on how yield return new waitforseconds works

in jave it is simple put into a function but with csharp it has to enumerable or something,what is this and how do i implement it into a function, this is a snippet

void tweenComplete(){
	audio.Stop();
//	yield return new WaitForSeconds(2);
	print ("hi");
}

Yeah UnityScript doesn’t need you to tell it the return value of the function (it does it invisibly).

In C# you need:

  IEnumerator tweenComplete() {
      ...
      yield return new WaitForSeconds(2);
      ...
  }

What yield does is it creates a “state machine” that uses IEnumerator to have it execute sections of your code in multiple goes. So the first time the code runs until the yield. Then afterwards it kicks back off from there…

Unity Script is also doing the same thing, but it’s hiding it. You’ll find that a lot - not so much magic stuff happens in C# and you have to declare things yourself. (Like you have to StartCoroutine() inside Update() etc rather than just calling the function).

you need to use StartCoroutine ( tweenComplete () ); In order to get the behaviour you expected. Just make sure to call it just once. Use a bool to make this control.

bool _callCoroutine;

void Start () {

_callCoroutine = true;

}

void Update () {

if(_callCoroutine) {

StartCoroutine ( tweenComplete () );
_callCoroutine = false;

}

}

Of course, as Mike said, it needs to return an IEnumerator.