Object Reference Not Set To an instance of an object?

Hey guys i have been working on a character controller and some cross platform UI and i am getting the error “Object Reference Not Set To an instance of an object” I am not sure why im getting this error since its set up as far as i can tell the same as the player controller. If anyone could help i would be greatful.

PlayerController

using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour {

    //Speed
    public float maxSpeed = 1f;

    //Facing
    public bool facingRight = true;

    //Animator
    private Animator anim;

    //Falling / Grounded
    private bool grounded = false;
    public Transform groundCheck;
    private float groundRadius = 0.2f;
    public LayerMask whatIsGround;
    public float jumpForce = 500f;
    public bool airMovment = false;

    public GameObject jumpEffect;

    private bool doublejump = false;

    // Use this for initialization
    void Start () {
        anim = GetComponent<Animator> ();
    }


    // Update is called once per frame
    void FixedUpdate () {
        //Are we Hitting any colliders in this circle (genrated circle postion,radius,what it will collide with) (true "on ground" / false "not on ground")
        grounded = Physics2D.OverlapCircle(groundCheck.position,groundRadius, whatIsGround);
        //Set ground animation
        anim.SetBool ("Ground", grounded);

        if (grounded)
            doublejump = false;

        anim.SetFloat ("vSpeed", GetComponent<Rigidbody2D>().velocity.y);

        //turn off air movment
        if (airMovment == true) {
            if (!grounded)
                return;
        }


    }

    public void Move (float move,  bool jump)
    {
        //If we are grounded and press space (single jump version)
        //if (grounded && Input.GetKeyDown (KeyCode.Space)) {


        //Abousle value of speed to set speed for animator.
        anim.SetFloat ("Speed", Mathf.Abs (move));

        //Get the component RidgitBody add a velocity to it at the rate of move times the max speed and leave y as it is.
        GetComponent<Rigidbody2D>().velocity = new Vector2 (move * maxSpeed, GetComponent<Rigidbody2D>().velocity.y);

        // If the input is moving the player right and the player is facing left...
        if (move > 0 && !facingRight)
        {
            // ... flip the player.
            Flip();
        }
        // Otherwise if the input is moving the player left and the player is facing right...
        else if (move < 0 && facingRight)
        {
            // ... flip the player.
            Flip();
        }

        if ((grounded || !doublejump) && jump && anim.GetBool("Ground")) {
            //Set the ground animation to false
            anim.SetBool("Ground", false);
            //Add a force to our Rigidbody2D on the y axis
            GetComponent<Rigidbody2D>().AddForce(new Vector2(0,jumpForce));

            //If we are grounded
            if (grounded)
            {
            //Create effect
                GameObject jumpE = Instantiate (jumpEffect, transform.position, Quaternion.identity) as GameObject;
                Destroy(jumpE,0.2f);
            }



            //Double jump (if we are not on the ground and have not double jumped then.. set it true
            if(!doublejump && !grounded)
            {
                doublejump = true;
            }
        }

    }
   

    private void Flip()
    {
            // Switch the way the player is labelled as facing.
            facingRight = !facingRight;
           
            // Multiply the player's x local scale by -1.
            Vector3 theScale = transform.localScale;
            theScale.x *= -1;
            transform.localScale = theScale;
    }
}

UserController

using System;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;

    [RequireComponent(typeof (PlayerController))]
    [RequireComponent(typeof (Bow))]

    public class UserControl : MonoBehaviour
    {
        private PlayerController m_Character;
        private Bow m_Bow;
        private bool m_Jump;
        private bool m_attack1;
        private bool m_attack2;
        private bool m_attack3;
       
       
        private void Awake()
        {
            m_Character = GetComponent<PlayerController>();
        }
       
       
        private void Update()
        {
            if (!m_Jump)
            {
                // Read the jump input in Update so button presses aren't missed.
                m_Jump = CrossPlatformInputManager.GetButtonDown("Jump");
            }

        if (!m_attack1) {
            m_attack1 = CrossPlatformInputManager.GetButton ("Fire1");
        }
        if (!m_attack2) {
            m_attack2 = CrossPlatformInputManager.GetButtonDown ("Fire1");
        }
        if (!m_attack3) {
            m_attack3 = CrossPlatformInputManager.GetButtonUp ("Fire1");
        }

        }
       

       
       
       
        private void FixedUpdate()
        {
            // Read the inputs.
            //bool crouch = Input.GetKey(KeyCode.LeftControl);
            float h = CrossPlatformInputManager.GetAxis("Horizontal");
            // Pass all parameters to the character control script.
            m_Character.Move(h, m_Jump);
            //Pass all parameters to the bow
            m_Bow.BowShoot(m_attack1,m_attack2,m_attack3);
            m_Jump = false;
            m_attack1 = false;
            m_attack2 = false;
            m_attack3 = false;
        }
    }

Bow

using UnityEngine;
using System.Collections;

public class Bow : MonoBehaviour {
   
    private Animator b_Anim;
    public Rigidbody2D shotArrow;
    public float arrowSpeed = 1.0f;
    private bool isFiring = false;
    private bool release = false;


    // Use this for initialization
    void Start () {
        b_Anim = this.GetComponent<Animator>();
    }

    void Update()
    {
        if (isFiring == false && release == true) {
            release = false;
            //stop the release animation
            b_Anim.SetBool ("Release", release);
        }
    }

    // Update is called once per frame
    public void BowShoot (bool attack1, bool attack2, bool attack3)
    {
        //On button pressed
        if (attack1){
            //We are firing
            isFiring = true;
            //Set animator to int 1
            b_Anim.SetBool("Drawn", true);
            //Show a debug message
            Debug.Log ("Drawn");
        }
        //Button held down
        if (attack2) {
            //Set animator to int 2;
            b_Anim.SetBool ("Hold", true);
            Debug.Log ("Hold");
        }
        //released
        if (attack3) {
            //Set drawn and hold to false
            b_Anim.SetBool ("Drawn", false);
            b_Anim.SetBool ("Hold", false);
            //change release to true (since we released the arrow
            release=true;
            //Play the animation
            b_Anim.SetBool ("Release", release);
            //Change firing to false
            isFiring = false;
            Debug.Log ("Release");
            //Shoot Arrow
            //Create Arrow and set its postion and as Rigidbody2D.
            var createArrow = Instantiate (shotArrow, transform.position, Quaternion.identity) as Rigidbody2D;

            //Get the players direction from player controller
            PlayerController direction = GetComponent<PlayerController>();
            //Store it in a variable
            bool dir = direction.facingRight;

            if (dir)
            {
            //Add Velocity to the right at speed.
                createArrow.velocity = transform.right * arrowSpeed;
            }
            else
            {
                createArrow.velocity = -transform.right * arrowSpeed;
            }
            //Create a arrow and add aforce to it on a vector 2 to the right by the speed.
            //createArrow.AddForce(Vector2.right * arrowSpeed);
        }



        }
    }

The issue seems to be with the passing infromation between the two scripts i think

Thanks for your help in advance! =]

Afternoon, could you paste in the error your getting please.

NullReferenceException: Object reference not set to an instance of an object
UserControl.FixedUpdate () (at Assets/Vigor SideScroller/Scripts/UserControl.cs:56)

^ in run time erorr.

Awake in playerControl should be

m_Bow = GetComponent<Bow>( );

In other words you forgot to initilaze your m_Bow variable in your playerControler

Omg thanks i completly missed that !

This is from the 3rd chapter of the first tutorial game. I am getting the following error at runtime:
“NullReferenceException: Object reference not set to an instance of an object
playerController.FixedUpdate () (at Assets/Scripts/playerController.cs:23)”

Thanks for the help in advance!

using UnityEngine;
using System.Collections;

public class playerController : MonoBehaviour 
{

 public float speed;

 private Rigidbody rb;

 void start()
 {
 rb = GetComponent<Rigidbody>();
 }


 void FixedUpdate()
 {
 float moveHorizontal = Input.GetAxis("Horizontal");
 float moveVertical = Input.GetAxis("Vertical");

 Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);

 rb.AddForce(movement * speed);
 }
 
}

@Gilfradus

Afternoon,
Just wondering, have you attached a Rigidbody component to the Object that this script is attached to?

Yes.

Start()

not

start()

1 Like

Well spotted, didnt see that one :slight_smile:

Wow. I can’t believe I missed that. It happens to the best of us i guess. Thanks for the help. I need to stick to using Visual Studio for my code, it’ll catch those small syntax errors. I was just typing fast so I missed that caps. Thanks again! :slight_smile:

Same issue. Seems like two problems.

NullReferenceException: Object reference not set to an instance of an object
PlayerController.RemoveFocus () (at Assets/JDT Scripts/PlayerController.cs:117)
PlayerController.Update () (at Assets/JDT Scripts/PlayerController.cs:50)

I believe it is lines 50 and 117 but I still cannot see what I am doing wrong.

Any help would be greatly appreciated! I’m very new. Trying my best to understand each line of code as I follow along Brackeys’ & Sebastian’s RPG tutorial, video 2.

7571008–937546–PlayerController.cs (1.19 KB)

Figured it out. I had this twice under my void RemoveFocus().

focus.OnDefocused();

This error NEVER needs a forum post and certainly not a necro post to a 6-year-old thread. Why?

Because it does not even matter what you are doing.

The answer is always the same… ALWAYS. It is the single most common error ever.

Don’t waste your life spinning around and round on this error. Instead, learn how to fix it fast… it’s EASY!!

Some notes on how to fix a NullReferenceException error in Unity3D

  • also known as: Unassigned Reference Exception
  • also known as: Missing Reference Exception
  • also known as: Object reference not set to an instance of an object

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.

You need to figure out HOW that variable is supposed to get its initial value. There are many ways in Unity. In order of likelihood, it might be ONE of the following:

  • drag it in using the inspector
  • code inside this script initializes it
  • some OTHER external code initializes it
  • ? something else?

This is the kind of mindset and thinking process you need to bring to this problem:

https://forum.unity.com/threads/why-do-my-music-ignore-the-sliders.993849/#post-6453695

Step by step, break it down, find the problem.

Here is a clean analogy of the actual underlying problem of a null reference exception:

https://forum.unity.com/threads/nullreferenceexception-object-reference-not-set-to-an-instance-of-an-object.1108865/#post-7137032