Herb Herb - 3 years ago 150
C# Question

Switch inside IEnumerator keeps looping

Hi folks I have this little 2D guy who has 2 states "IsSpeaking" and "Silence" I use them to make the Animator set a bool to true or false and the character seems to be speaking.

I need that the IsSpeaking lasts a different amount of time depending on the amount of text that is displayed on screen like this:

Text dialogueNumber(X) appears
Animate Speaking
Wait "X" time...
Animate Idle
Wait in Idle for next text (dialogueNumber) to appear and restart cycle...


I tried to do this with this little code:

void Update () {
StartCoroutine(IsSpeaking());
}

IEnumerator IsSpeaking()
{
switch (dialogueNumber)
{
case 0:

yield return null;

break;

case 1:

functionsScript.IsSpeaking();
yield return new WaitForSeconds(3);
functionsScript.Silence();
yield break;

case 2:

functionsScript.IsSpeaking();
yield return new WaitForSeconds(6);
functionsScript.Silence();
yield break;
}
yield break;


So the longer the text the longer the Wait time to switch to the silence animation but it seems works fine the first time (case 1) and after it goes to silence it keeps going going back and forth randomly from IsSpeaking to Silence, I'm not sure if this was the best way to achieve this or if there's a better way to switch between states and wait an amount of time?

Thanks a lot for the advice...

Answer Source

Indeed my problem had a bad approach it was easier to make this outside the update function, turned out to be easier to set the number in the same "Next" button as a function called inside the On Click() resulting in something like this:

     public void TextID()
       {
         textID= (int)VD.nodeData.extraVars["cuadro"];
         print(textID);

             switch (textID)
             {
               case 0:
               break;

               case 1:
               StartCoroutine(LipsMoving(3));
               break;

               case 2:
               StartCoroutine(LipsMoving(6));
               break;
             }

        }

        IEnumerator LipsMoving(int talkTime)
         {
          funcionesScript.Speaking();
          yield return new WaitForSeconds(talkTime);
          funcionesScript.Idle();

          yield return null;
         }

In this way I get the frame ID as the user clicks the button and also runs my coroutine without weird loops. Thanks again for the help and patience it's refreshing to have different points of view to find the right way, hope this is useful to you guys

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download