0
votes

I'm a newby in Unity and I'm following the first Unity tutorial. When i try to run my first script i get this error:

NullReferenceException: Object reference not set to an instance of an object

Here is my script:

#pragma strict
private var rb:Rigidbody;
private var player:GameObject;

function start() {
    player = GameObject.Find("Player");
    rb = player.GetComponent(Rigidbody);
}

function FixedUpdate() {
    var moveHorizontal:float = Input.GetAxis("Horizontal");
    var moveVertical:float = Input.GetAxis("Vertical");

    var movement:Vector3 = new Vector3(moveHorizontal , 0.0f , moveVertical);
    rb.AddForce(movement);
}

I have no idea what am I doing wrong.

UPDATE:

Here is my scene:

enter image description here

UPDATE: I've put print in both functions, and it seems like start is not being called at all, and that is why my variable is not being initialized. Any idea?

4
This has nothing to do with JavaScript. You probably meant UnityScript. For some confusing reasons they advertise it as JavaScript and use .js file extension, but UnityScript is vastly different from JS. - MichaƂ Miszczyszyn

4 Answers

3
votes

I would remove the declaration

private var rb:Rigidbody;

because it seems that your script is trying to access the declared Rigidbody (that stills not initialized, so it's null), and not the object's real one.

Side note: seems that, from Unity 5.3.3, you have to do:

player.GetComponent.<Rigidbody>(); 

(from here)

1
votes

It seems your gameobject doesn't have Rigidbody component attached to it and variable rb is null after rb = GetComponent(Rigidbody);

1
votes

You should take advantage of "Unity way" to reference variables. I mean, your player and rb attributes must be public and you just drag into it your gameobject from hierarchy to your attribute on inspector.

If you still want to do it private, for some good reason, just change player = GameObject.Find("Player"); for player = GameObject.FindWithTag("Player"); and your null reference probably will be solved.

0
votes

So finally after a few hours, I got it. The problem was that start function should be upper case Start. Since it was lowercase, it wasn't called and rb was not initialized.

And here is the final script:

#pragma strict
private var rb:Rigidbody;


function Start() {
    rb = GetComponent(Rigidbody);
}

function FixedUpdate() {
    var moveHorizontal:float = Input.GetAxis("Horizontal");
    var moveVertical:float = Input.GetAxis("Vertical");

    var movement:Vector3 = new Vector3(moveHorizontal , 0.0f , moveVertical);
    rb.AddForce(movement);
}