Search Unity

Unity animation from foreach loop c# skips third call each time.

Discussion in 'Animation' started by JeremyToler, Feb 25, 2018.

  1. JeremyToler

    JeremyToler

    Joined:
    Jul 11, 2015
    Posts:
    22
    I have a UI text that I update in script off camera then uses an animation to have it slide across the screen. The script uses a foreach loop since the text change and number of times the animation runs are variable. It always skips the third animation (it will print the effect in console but will not play that animation), even when 4 or 5 effects are called. Below is the code i'm using to call the animation, and I have a poor quality video of the error behavior at the bottom of the post.

    Code (csharp):
    1. private Animation Anim;
    2. public Text NBtext;
    3. public GameObject NBEffect, Tut, TouchInput;
    4. public IEnumerator NiceBowlingEffects(List<string> Effects, bool FirstFrame)
    5. {
    6.    Anim = GetComponent<Animation>();
    7.    NBEffect.SetActive(true);
    8.    yield return new WaitForSeconds(.2f); //give frame ect a chance to load.
    9.    foreach (var Effect in Effects)
    10.    {
    11.        NBtext.text = Effect;
    12.        Print(Effect); //Prints to consol here every time
    13.        Anim.Play(); //Does not run this the third time?
    14.        yield return new WaitForSeconds(Anim.clip.length);
    15.    }
    16.    NBEffect.SetActive(false);
    17.    if (FirstFrame)
    18.    {
    19.        Tut.SetActive(true);
    20.    }
    21.    TouchInput.SetActive(true);
    22. }

     
  2. JeremyToler

    JeremyToler

    Joined:
    Jul 11, 2015
    Posts:
    22
    Hopefully this helps someone but to finally get this to work for Nice Bowling I had to add a time delay between changing the text and playing the animation. Here's the code that's running on Nice Bowling right now.

    Code (CSharp):
    1. public IEnumerator NiceBowlingEffects(List<string> Effects, bool FirstFrame)
    2. {
    3.     Anim = GetComponent<Animation>();
    4.     NBEffect.SetActive(true);
    5.     yield return new WaitForSecondsRealtime(.1f); //give frame ect a chance to load.
    6.     foreach (var Effect in Effects)
    7.     {
    8.         NBtext.text = Effect;
    9.         yield return new WaitForSecondsRealtime(.1f); //text time to change
    10.         Anim.Play();
    11.         yield return new WaitForSecondsRealtime(Anim.clip.length +.01f);
    12.     }
    13.     NBEffect.SetActive(false);
    14.     if (FirstFrame)
    15.     {
    16.         Tut.SetActive(true);
    17.         Tut.GetComponent<UISprite>().Trigger();
    18.     }
    19.     TouchInput.SetActive(true);
    20. }
     
unityunity