- Home /
Have null errors
Have two scripts to move an object(witch script Follower) to a spot(with a script Leaders). But i get null error at start,and when im clicking at a spot. Thanks for any help!
public class Follower : MonoBehaviour {
public Vector3 v3Dest;
public float speed = 5.0f;
void Start () {
v3Dest = transform.position;
}
void Update () {
transform.position = Vector3.MoveTowards(transform.position,v3Dest,Time.deltaTime * speed);
transform.LookAt(v3Dest);
}
}
public class Leaders : MonoBehaviour {
private Follower follower;
void Start () {
follower = GameObject.Find ("Follower").GetComponent< Follower >();
}
void OnMouseDown() {
follower.v3Dest = transform.position;
}
}
Answer by CHPedersen · May 10, 2013 at 10:31 AM
This occurs because the attempt to locate the gameobject "Follower" fails.
You get one NullReferenceException in Start because:
GameObject.Find ("Follower")
cannot find "Follower", and returns null, and then trying to call GetComponent();
on "null" throws the exception.
You get a NullReferenceException in method OnMouseDown every time you click the mouse because follower was never succesfully set in Start, so accessing its v3Dest member throws the exception.
Check to see if your scene truly contains a gameobject whose name is "Follower".
You are right, i forgot to rename my object, thanks!
Edit: I truly loathe Unity Answer's way of handling less-than / greater-than signs. That's supposed to say:
GetComponent<Follower>();
But I cannot for the life of me get it to display properly.