Enums not letting me compare in If Statement

Hullo,

I have an enum declared inside a script called PlayerCharacter, like so, and a global variable declared too. Like so.

enum State {walking, attacking, turning}

var state : State;

Now, this script is attached to the player character. I have all sorts of other scripts attached too that access the PlayerCharacter script and check the state, like so.

	if (playerCharacter.state == State.walking)
	{
//DOOO something
}

With playerCharacter being the variable I assigned the PlayerCharacter script to, using GetComponent. This all works fine and dandy, and everyone’s happy.

However, when I try to do this exact same comparison outside of the PlayerCharacter object, it doesn’t seem to want to compile. Inside another script, I have,

function OnTriggerEnter(col : Collider)
{
	if (col.gameObject.tag == "Player")
	{
		playerCharacter = col.gameObject.GetComponent(PlayerCharacter);
		Debug.Log(playerCharacter.state);
		if (playerCharacter)
		{
			if (playerCharacter.state == State.walking)
			{
				//dooo something
			}
		}
	}
}

Now, if I comment out the last if statement, the Debug.Log returns “walking”. So I do have proper access to the variable state. However, when I try to compile this, I get error

Operator ‘==’ cannot be used with a left hand side of type ‘System.Object’ and a right hand side of type ‘State’

This is boggling my mind. I’m fairly new to using enums, but I really don’t get this. I was under the impression that enums were special or global or something, but I really don’t see any connection to why this statement works inside the Player object, but not outside.

Thanks for any help!

This is not a problem with enums. This is a problem with variable typing.

var playerCharacter : PlayerCharacter;

playerCharacter = col.GetComponent.<PlayerCharacter>();

Use #pragma strict, always. :slight_smile:
(Well, actually, use C#. But barring that…)

Alright, it compiles! Not quite sure I fully understand why though, I get that it relates to variable typing, but it seemed to be the right type when I debug.logged it (as it showed up as “walking”).

It might have something to do with your lack of the keyword var; I don’t know if that’s your whole script.