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. Voting for the Unity Awards are OPEN! We’re looking to celebrate creators across games, industry, film, and many more categories. Cast your vote now for all categories
    Dismiss Notice
  3. Dismiss Notice

[SOLVED] Efficient Way to Change Animations?

Discussion in 'Scripting' started by ChrisIsAwesome, Oct 15, 2018.

  1. ChrisIsAwesome

    ChrisIsAwesome

    Joined:
    Mar 18, 2017
    Posts:
    183
    I have a series of animator parameters that I'd like only one to be true at a time (for the most part), so one way of doing it is this:

    Code (CSharp):
    1. anim.SetBool ("isIdle", false);
    2. anim.SetBool ("isWalking", true);
    3. anim.SetBool ("isJumping", false);
    4. ... etc.
    But that is very messy and inefficient. I know there would be a way to loop through each parameter with a for loop and I've looked up ways of doing this but it's not working. I've tried this:

    Code (CSharp):
    1. for (int i = 0; i < anim.paramaters.Length; i++)
    2. {
    3.      anim.ResetTrigger (i);
    4. }
    And although the above code does loop through each parameter, it does not reset the triggers nor the booleans using the i variable.

    Any help would be greatly appreciated!
     
  2. Baste

    Baste

    Joined:
    Jan 24, 2013
    Posts:
    6,186
    ResetTrigger(int) takes the hash of the parameter name. Sadly, there's no way to get the states of the animator controller at runtime.

    The easiest thing is to build an array of the hashes at startup:

    Code (csharp):
    1. private int[] boolHashes;
    2.  
    3. void Awake() {
    4.     boolHashes = new int[] {
    5.        Animator.StringToHash("isIdle");
    6.        Animator.StringToHash("isWalking");
    7.        Animator.StringToHash("isJumping");
    8.        ...
    9.     };
    10. }
    11.  
    12. ...
    13.  
    14. // when you want only isWalking true
    15. foreach(var hash in boolHashes) {
    16.     anim.SetBool(hash, false);
    17. }
    18. anim.SetBool("isWalking", true);
    Alternatives is to design your animator so you don't have to do this, or use a different way of animating. SimpleAnimation is a good alternative. Somebody linked the lite version of Animancer the other day, it looked pretty decent as well.
     
    ChrisIsAwesome likes this.
  3. ChrisIsAwesome

    ChrisIsAwesome

    Joined:
    Mar 18, 2017
    Posts:
    183
    Thank you! Just as a correction, commas after each element in the array, not semicolons ;)
     
    Baste likes this.