- Home /
The character controller return null refrence
I try to make my character move by using CharacterController but the problem is in the run time it tell me that the character controller does not match with any anything and the character do not move at all, so is there any falt in the code:
Here is my code:
using UnityEngine;
using System.Collections;
public class Move {
Transform transform;
float gravity = 9.8f;
float speed = 3f;
float jumpSpeed = 0.3f;
Animation animation;
CharacterController controller = new CharacterController();
Vector3 moveDirection = Vector3.zero;
public void Moving() {
controller = (CharacterController)controller.GetComponent(typeof(CharacterController));
transform.Rotate(0, 2 * Input.GetAxis("Mouse X"),0);
if(controller.isGrounded){
moveDirection.x = 0;
moveDirection.z = 0;
if(Input.GetKey("up")){
moveDirection = transform.TransformDirection(Vector3.forward);
controller.Move(moveDirection * Time.deltaTime * speed);
animation.Play("walk");
}
if(Input.GetKey(KeyCode.Space)){
moveDirection = transform.TransformDirection(Vector3.forward);
controller.Move(moveDirection * Time.deltaTime * speed);
animation.Play("run");
}
if(Input.GetKeyUp(KeyCode.Space)){
animation.Play("idle");
}
if(Input.GetKey("down")){
moveDirection = -transform.TransformDirection(Vector3.forward)* 2;
controller.Move(moveDirection * Time.deltaTime * speed );
animation.Play("walk");
}
}
moveDirection.y -= gravity*Time.deltaTime;
controller.Move(moveDirection * Time.deltaTime);
}
}
Are you sure that the character controller is attached to the same object that your script is attached to? GetComponent only looks at the object it is declared on. GetComponentInChildren looks at it's own object and all child objects looking for a match.
Answer by Doireth · Jan 17, 2013 at 08:19 PM
The line
controller = (CharacterController)controller.GetComponent(typeof(CharacterController));
Is getting the character controller component of the controller object, which doesn't make sense. Try instead
controller = (CharacterController)transform.GetComponent(typeof(CharacterController));
Answer by Loius · Jan 17, 2013 at 06:09 PM
You can't create new components (you can't ever do "new CharacterController", or any other type of Component). You have to use AddComponent.
Unless you're changing things into characters on the fly, you'll want to add the CharacterController component in the editor, not through script. Then your code will work (if you take out the new line, and have the controller on the same object as this script).
I already removed GetComponent part and added this line:
controller = (CharacterController)gameObject.AddComponent(typeof(CharacterController));
and still have the same problem