Unity String Reference Workaround

I just wanted to share in case anyone else finds this useful. It’s very basic, but I’ve been doing something similar for years in most of my projects, Unity or otherwise.

String references can be a pain in the butt, and copy-pasting them from Unity into the scripts is just obnoxious and annoying. Instead of being constantly annoyed by them cluttering up my code, I always end up making a class of constants to reference. Also, this way if I ever do want to change the string, it is much less nerve-wracking to do so.

For Example, instead of using this:

animator.SetTrigger( "attack" );    // after having made sure to copy/paste it correctly, often in many locations.

I can simply use this:

animator.SetTrigger( StringReferences.STOP_ATTACK_TRIGGER );

to access constant variables in my unity project

namespace RPG.Core   // A simple class to keep the string parameters Unity
	static class StringReferences
		// From Character Animator Controllers (types: Float, Int, Bool, Trigger)
		public const string FORWARD_SPEED_FLOAT = "forwardSpeed";
		public const string ATTACK_TRIGGER = "attack";
		public const string DIE_TRIGGER = "die";
		public const string STOP_ATTACK_TRIGGER = "stopAttack";

Sometimes the names are longer/more descriptive (ANIMATOR_CHAR_TRIGGER_ATTACK) or I put a few classes in the file (one for character parameters, one for effects, etc) depending on how many string references my project has and if I feel it needs to be split up more for quicker access. I’ve done it via Dictionaries, enums, and other grouping methods, but have found this to be the simplest and fastest option to just get going.

Does anyone else have things they do to cut down on typo errors? If so, please share, I’d love to hear them! :grinning:

This is an excellent suggestion, and is a widely used solution for the magic string problem.

Well done!