How to fix NullReferenceException

Hello everyone, I have a problem with NullReferenceException, but this error does not affect the compilation of the code, my player still moves correctly. But annoying error messages appear in the console. Here’s the code:

public class PlayerPlatformerController : PhysicsObject {

    public float maxSpeed = 7;
    public float jumpTakeOffSpeed = 7;

    private SpriteRenderer spriteRenderer;
    private Animator animator;
  
    public Joystick Joystick;

    // Use this for initialization
    protected override void ComputeVelocity()
    {
        Vector2 move = Vector2.zero;
        if (Joystick.Horizontal > .5f)
        {
            move.x = Joystick.Horizontal;
        } else if (Joystick.Horizontal < -.5f)
                move.x = Joystick.Horizontal;
            else move.x =0;

        if (Joystick.Vertical > .8f && grounded) {
            velocity.y = jumpTakeOffSpeed;
        } else if ( Joystick.Vertical < .8f && grounded == false)
        {
            if (velocity.y > 0) {
                velocity.y = velocity.y * 0.5f;
            }
        }
        targetVelocity = move * maxSpeed;
    }
}

Here is the error message:

6182198--677186--H9diaLVd.png

Error code tells you the line of the null reference. I’m going to guess that your Joystick variable is null as you have omitted a few lines of code.

Some notes on how to fix a NullReferenceException error in Unity3D

  • also known as: Unassigned Reference Exception
  • also known as: Missing Reference Exception

http://plbm.com/?p=221

The basic steps outlined above are:

  • Identify what is null
  • Identify why it is null
  • Fix that.

Expect to see this error a LOT. It’s easily the most common thing to do when working. Learn how to fix it rapidly. It’s easy. See the above link for more tips.

Thank you for your reply, i fixed it by simply add this string of code:
Joystick = FindObjectOfType();

1 Like