After little experiment I have found that it is forbidden to use SetBool (or any other Set in Animator, like SetTrigger, SetFloat) with input parameter string name.
Use SetBool (int id) , if you want to get maximum performance.
According to my tests, SetTrigger with string is 2x slower than with ID !
Performance tests:
Call count: 1 000 000 000.
SetTrigger (string name) - 1:52 (min, sec)
SetTrigger (int id) - 0:55 (min, sec)
StringToHash (string name) - 1:18 (min, sec) - just to test speed of this function. You need to call it only once and save the returned id.
What is that id ? How do I get it ?
This is not index of your parameter in the Animator window.
To get id you need to call Animator.StringToHash(string name) at Start or Awake (just only once), where name is name of parameter which you used in SetBool(string name). StringToHash returns ID, as integer.
Anyways, one call of SetBool (string name) will be absolutely not a big task, but âint idâ will be faster
Thank you.
I am making different performance tests fairly often, so I decided to start publishing them to the forum.
Watch for my topics, Iâll upload something else during the current week.
Note that there is a very small chance of getting a collision with using the hash. In other words two strings used for a trigger could result in the same hash value.
You can avoid Animator Controllers and Magic Strings and just directly reference the AnimationClips you want to play if you use Animancer (link in my signature).
But if you are going to keep using Animator Controllers, donât call StringToHash in Start or Awake like OP suggested, call it in a static field initialiser so that it only has to run once when that script type is initialised instead of once for every instance of the script:
public static readonly int MyBool = Animator.StringToHash("MyBool");
I believe it can be very slightly faster in some cases, but the main reason to use it is to ensure that nothing else accidentally reassigns the value and breaks your animation code.
I use static readonly int to set the character falling state to âtrueâ => animator.SetBool(Fall, _character.IsFalling()); which works fine, but I canât set the int ID to âfalseâ. animator.SetBool(Fall, false); is not disabling it. Can you advice what should be done to set it as âfalseâ?
That would do it so your problem must be elsewhere. Maybe your code isnât running that line or you have multiple copies of the script or character in the scene and youâre looking at the wrong one.