Tomer
Tomer

Reputation: 17940

Unity: getting NullReferenceException using javascript

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?

Upvotes: 0

Views: 302

Answers (4)

Tomer
Tomer

Reputation: 17940

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);
}

Upvotes: 0

Frohlich
Frohlich

Reputation: 963

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.

Upvotes: 1

Andrea
Andrea

Reputation: 6123

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)

Upvotes: 3

izeed
izeed

Reputation: 1731

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

Upvotes: 1

Related Questions