Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Random animation array not working

Discussion in 'Scripting' started by cristo, Aug 25, 2019.

  1. cristo

    cristo

    Joined:
    Dec 31, 2013
    Posts:
    265
    Does anyone know why this doesn't work? It seems to only call one animation. If I put
    Code (CSharp):
    1. this.GetComponent<Animation>().Play("Three");
    into the update function it works. Or any of the other single animations. But this random array isn't working.

    Code (CSharp):
    1.  
    2.  
    3.     private string[] _animationNames = new string[] { "One", "Two", "Three", "Four", "Five" };
    4.     void Start()
    5.     {
    6.  
    7.     }
    8.     //Public Void OnTriggerEnter()
    9.  
    10.     void Update()
    11.  
    12.     {
    13.         this.GetComponent<Animation>().Play(_animationNames[Random.Range(0, _animationNames.Length)]);
    14.  
    15.     }
    16. }
     
  2. tonemcbride

    tonemcbride

    Joined:
    Sep 7, 2010
    Posts:
    1,077
    The 'Update' function gets called every frame so your code will be starting different animations loads of times each second. Does it not work if you put it in the Start function?
     
    cristo likes this.
  3. cristo

    cristo

    Joined:
    Dec 31, 2013
    Posts:
    265
    Thanks for the feedback