Check Available Variables of Mecanim Animator

Is there a way to check which variables I can set on a Mecanim animator?

I have lots of NPCs with sets of animation clips that I want to select from at random. For example, here’s a set of Idle animations:

So I simply added a Variable called Random100 to all my animators that is, once per second, assigned a random number between 0 and 99, allowing my Mecanim state machine to transition (eg. with 30% likelihood it could transition to StandAround or LookBored, with 10% likelihood it could transition to Stretch, Yawn or ScratchHead.

It would be nice it I could make this Random100 a built-in feature of my controllers that, when present, gets fed a random number regularly. However, I couldn’t find a convenient HasInteger() or similar method to detect whether there is a variable called Random100 in my animator.

Is there a way to check for this?

I know this is quite an old thread but it hasn’t really been answered so thought I’d share my solution.

I wrote the following extension method for Animator:

public static partial class AnimatorExtensions {

	public static bool HasParameterOfType (this Animator self, string name, AnimatorControllerParameterType type) {
		var parameters = self.parameters;
		foreach (var currParam in parameters) {
			if (currParam.type == type && currParam.name == name) {
				return true;
			}
		}
		return false;
	}

}

You can now test if a given parameter exists on an animator instance using:

Animator myAnimator = GetComponent<Animator> ();
bool hasMyParam = myAnimator.HasParameterOfType ("MyParam", AnimatorControllerParameterType.Int);

it’s also easy to write a version which compares ‘nameHash’ instead of ‘name’ if that’s more useful to you.

When you try to read from a variable, you get an error if it doesn’t exist. You can catch that error to see if it exists or not.

This is a very basic programming concept. Not related with Unity at all.

I don’t think this functionality has been exposed yet, not even in Unity 4.2. At least I don’t see it in any of the release notes or documentation.

I know it’s far from ideal, but what about adding a set of Boolean parameters guaranteed to exist on all of your animator controllers that indicate what the controller supports – for example, a hasRandom100 Boolean that you can check.

You mean parameters?

Use this recent addition to the API (I think)

http://docs.unity3d.com/ScriptReference/Animator-parameters.html