Best way of using animator bools in a script

Hey, sorry if the title is strange, i kinda don’t know exactly what to type in as a title. Anyway, i am intrigued. I am working on a mobile game, and i am doing my best to keep everything as smooth and mobile friendly as possible, but i am facing a problem with a script of mine.

I have two “tilt” animation for my character for when the player is rotating the device, and i want to trigger them accordingly. For now i am testing only on the PC, and i really want answers for PC too bcs i know how to translate them to mobile later. Here is an example of what i am using:

void Update()
{
       If (Input.GetKey("a")
        {
             anim.SetBool("TiltLeft",true);
        }

       If (!Input.GetKey("a")
        {
             anim.SetBool("TiltLeft",false);
        }
}

But to be sincere, this method is horrible for performance, as it is placed on Update. I was thinking about adding a void LateUpdate and place the code there, but this would mean to have two… “fast” voids at the same time. I thought about using a bool, but this would also be insignificant. My question is: What would be the best method to implement this “dynamic” bool system into my script?

As a word of advice, first thing you need to do is make hashes of your animation strings in Awake () or Start () maybe. Hash is basically int and processing int is faster than processing string as it doesn’t create garbage.

To do that create a variable, like:

private int tiltLeftBoolHash;

void Awake ()
{
       tiltLeftBoolHash = Animator.StringToHash("TiltLeft");
}

If you check the overloaded method of SetBool, you will notice that it also takes input parameter of int instead of string.

You can also look it up at these links:

Now coming on to the main point, you can do something like this:

if (Input.GetKeyDown(KeyCode.A))
{
       anim.SetBool(tiltLeftBoolHash, true);
}

if (Input.GetKeyUp(KeyCode.A))
{
       anim.SetBool(tiltLeftBoolHash, false);
}

Instead of checking in if whether the a is being currently pressed or not pressed, I think the more appropriate way is to use Down and Up variations of GetKey. GetKeyUp is only called in Update in that frame when you pressed the a key. Its not called after that. GetKeyDown is only called in Update in that frame when you released the a key.

Do let me know if it helps.

if you also checked for the value of the animator bool in your if statements you significantly reduce the amount of times that the SetBool function is called. I’m not sure that this is the most efficient way but it should help .

 void Update()
 {
        If (Input.GetKey("a") && !anim.GetBool("TiltLeft")
         {
              anim.SetBool("TiltLeft",true);
         }
 
        If (!Input.GetKey("a") && anim.GetBool("TiltLeft")
         {
              anim.SetBool("TiltLeft",false);
         }
 }