String “auto-completion”, Tags and Hash IDs

Unity Tags, Layers and Animator components are great tools to use, but they have one drawback: It is necessary to pass strings into certain MonoBehaviour methods to make them work.

Consider this short example:

There are several situations in which you can’t get around using strings as parameters for certain Unity methods. Other times it might be the most convenient and practical solution.

At this point it would be too much to talk about all the implications of using strings and how or why to avoid them. Instead, I’d like to show you a remedy for one of the many downsides of using strings in functions.

Strings as method parameters are difficult to deal with because of possible spelling-errors or tedious renaming of multiple string-instances.

The most common examples of string usage in methods are:

  • Output messages for console logging, warning messages and exceptions.
  • Accessing Animator layers and parameters
  • Identifying objects by Tag
  • Calling a method by name when using Invoke() or a Coroutine

A good solution for working with anything Animator related is to hash strings to integers and feed the Animator with ID’s instead of layer and parameter names. Int variables are much better for performance than strings. They also have the benefit of being visible in IntelliSense.

Create this script and attach it to a GameObject in the scene (Awake must be called for the StringToHash() method to create our ID’s):

I prefer to declare my hash variables as static, because then I can access them without finding a reference to them from other scripts. (A drawback is, that Unity’s debug inspector does not show static fields, so you have to set breakpoints or print to the console, if you want to debug your strings and hashes.)

If you’d like to use auto-completion on string parameters to easily remember them and prevent spelling-errors, try this:

Note, that a class which only stores variables doesn’t need to be attached to a GameObject. You can also declare multiple classes within one file.

"Auto-completion" for string values through static class.
“Auto-completion” for string values through static class.


Recap: Use hash ID’s for Animator layers and parameters. Store strings that will not change in a static class.