Why am i getting NullReferenceException?

Can anybody tell me why am i getting NullReferenceException because of:

//part of the script.
var joystick : Joystick; //using joystick from mobile assets.
var V1 : Vector2 = new Vector2(joystick.position.x,joystick.position.y); //float variables.

My guess is that nothing is assigned to joystick in the editor.

Because you didn’t set the value of joystick. You only set its type.

I think I see why you might be getting the error. Correct me if I’m wrong but

  • you have assigned joystick a value by dragging an object/prefab into it in the editor
  • thus you are expecting it to be valid when that line of code (for V1) executes

however this isn’t really what happens internally. Assuming your lines of code are declarations of member variables, the assignments are part of the object’s constructor. i.e. they get executed the moment the object is allocated in memory.

Now in unity, when the object is actually created, it will go through a few steps:

  • first, your object is allocated
  • next, its constructor is called
  • next, the data setup in the property editor is ‘deserialised’ into it
  • finally, the Start function is called on it (if you’ve provided one)

So even though you might think you’ve assigned something to joystick, when that line of code is executed internally it hasn’t been setup yet.

To do this kind of initialization, where you’re dependent on values the user has specified in the property editor, add it into your start function. So you should declare the V1 variable as a member where you are doing, but don’t assign it anything. Then add your:

V1 = new Vector2(joystick.position.x,joystick.position.y);

Inside the Start function.

The start function is guaranteed to be executed after unity has poked in all the property editor values so things will be setup correctly. As a rule, put any remotely complex initialization in here.

Hope that helps

-Chris