Using Animator.StringToHash, doing something like:
public static readonly int MyBool = Animator.StringToHash("MyBool");
Could anyone explain why one would do this?
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It only takes a minute to sign up.
Sign up to join this communityThis has to do with the speed of looking up data.
When you want to assign a new value to a parameter on an animator, Unity has to find where that parameter sits in memory, to be able to put the new value in the right place.
Think of it like trying to find the right office or classroom in an unfamilar building. If someone gives you a description, "It's the room with the door labelled 'Department of Impossible'", then you have to visit every door in some sequence, checking the label on each door, until you find the right one.
But if someone gives you the room number "3042", you're in much better shape. Now you know to start on the third floor, and if a sign in the hallway says "⬅ 3001-3050" then you know to go left, not right. When you find room 3039, you might reasonably guess that your destination is another two doors down, on the other side of the hall. All this helps you find your way to the right place faster.
Analogous things happen inside the computer: having an integer index or key makes it much faster to find the right item in memory.
To avoid the long exhaustive search for a matching string name, it's common to use what's called a Hash Table (in C# you'll see them used in the Dictionary
and HashSet
collections). Here we take the initial label we're looking for, then run it through some math called a hash function that turns it into a random-looking number (called a hash), so that we (usually) get different numbers for different labels, but always the same number whenever we put in the same label. Then we can use the much faster number-guided lookup strategies to find the data quickly.
But running that hash function has a cost of its own - especially if we're starting with a long string. We have to loop over each character in the string and to some work on it. And if we need to ensure the hashes are always unique, as in this case, then we may have some extra work to do on top of that. All to just get a number that's always going to be the same for a given input anyway.
So instead of re-doing this hashing work every time we want to set a parameter, every frame, for every one of a hundred animated characters, we can do it just once, and store the number we get. Then later, we can just look up the parameter by number, without doing the messy string hashing work every time.
static
ensures that only one copy of this number is stored in memory, and assigning it right in the initializer like that means we do the hashing work at start-up, just before the class is used for the first time. Then it's practically free to re-use for all our future parameter-twiddling needs.