I have seen several posts where the issue turned out to be an animation parameter that had a typo. While the issue cannot really be prevented with 100% certainty (that I am currently aware of), it can be mitigated.
What we can do is to reduce the number of times we have to type the name of the animation parameter. We can do this using constants. Once these constants are defined, we can use the constant instead of the string, and the compiler will immediately let us know if we made a typo and even better, give us some autocomplete.
I like to put constants like this in its own class for better organisation
// This class will hold ALL the animation parameters
public static class AnimationParameters
{
// This class will hold the parameters for a specific unit (animation controller)
public static class Player
{
public const string IsWalking => "IsWalking"; // this must match the parameter name
}
}
This is a small example. From here, we never have to write the parameter name again, reducing the chance of a typo. We can use it like this:
_animator.SetBool(AnimationParameters.Player.IsWalking, true);
Now, since we have this neatly encapsulated somewhere, we can go one step further and optimise it just a little. Instead of putting the string in a constant, we can get the hash value, and use that instead. For this we can no longer use constants because constants require a constant value which we don’t have. But we can still achieve what we want
// This class will hold ALL the animation parameters
public static class AnimationParameters
{
// This class will hold the parameters for a specific unit (animation controller)
public static class Player
{
private static int _isWalking = Animator.StringToHash("IsWalking"); // this must match the parameter name
public static string IsWalking => _isWalking;
}
}
The usage for this is exactly the same as for constants
_animator.SetBool(AnimationParameters.Player.IsWalking, true);
It’s perhaps a little overkill if you have one or two parameters that you only ever use in one place, but if they are used often in several places, this will help some.
Another option is to use extension methods. I have not initially mentioned this, because an extension method will not distinguish between animators.
// extension methods class
public static class AnimatorExt
{
public static void IsWalking(this Animator animator, bool isWalking)
=> animator.SetBool("IsWalking", isWalking); // string must match parameter (or use the constants/hash from above)
}
// usage
_animator.IsWalking(true);
This works, too, and reduces the number of times we have to type the parameter name, but all animators will now have a IsWalking(bool)
method, even if there is no “IsWalking” parameter