anim = GetComponent("Animator") is not working

This is probably very simple, but I’m new at this…
I’m trying to make a 4-way 2D movement script and everything works fine until I start messing with animations.
My current problem is that the script component at the bottom of this

should look like this when I reset it, but it doesn’t.

33294-scriptcomp.png

I know there’s something I’m missing, but I can’t figure out what it is, and nothing I’ve found online has helped.
this is the script. Hopefully it worked, because the code formatting doesn’t seem to work for me all the time…

var Speed : float = 0.5; // Movement Speed
static var Move : int = 1;
var IsMoving : boolean = false;
var anim : Animator; // The animator

function Start () 
{
    anim = GetComponent(Animator);
}

function Update(){
	if(IsMoving == true){
		IsMoving = false;
	}
	
	if(Input.GetKey(KeyCode.UpArrow) && IsMoving == false){
		transform.Translate(Vector2(0, Speed),Move);
		IsMoving = true;
		anim.SetInteger("Direction", 3); // Direction the character is facing. 0, 1, 2, 3 = down, left, right, up
	}

	if(Input.GetKey(KeyCode.DownArrow) && IsMoving == false){
		transform.Translate(Vector2(0, Speed * -1),Move);
		IsMoving = true;
		anim.SetInteger("Direction", 0);
	}

	if(Input.GetKey(KeyCode.RightArrow) && IsMoving == false){
		transform.Translate(Vector2(Speed,0),Move);
		IsMoving = true;
		anim.SetInteger("Direction", 2);
	}
	
	if(Input.GetKey(KeyCode.LeftArrow) && IsMoving == false){
		transform.Translate(Vector2(Speed * -1,0),Move);
		IsMoving = true;
		anim.SetInteger("Direction", 1);
	}
}

You don't need the "" in GetComponent("Animator"); you only need GetComponent(Animator); http://docs.unity3d.com/ScriptReference/GameObject.GetComponent.html

Oh, thanks. Darn, was really hoping that would fix it.

1 Answer

1

When you have the animator as a variable, and you assign it from the editor, you don’t have to use GetComponent to make it available - it’s already there for you. Just cut your entire Start method.

The thing you need to assign from the editor (drag and drop), by the way, is the object with the animator on it - not the animator asset in your assets folders. Which means that in your case, you have to drag the game object onto it’s own script.

Thanks. It looks like it works now anyway...which is weird... Now it's setting the object to the animator automatically when I start moving it while testing. Not entirely sure what happened... Removing the start method doesn't seem to have done anything, but removing the quotes did. I still removed the start method since I guess it doesn't do anything anyway.