Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question Object reference not set to instance of an object.

Discussion in 'Scripting' started by Froggles01, Apr 2, 2021.

  1. Froggles01

    Froggles01

    Joined:
    Apr 2, 2021
    Posts:
    8
    I just got Unity about a week ago, and I am quite new to C# as well. I am confused about the fact that unity is giving me an error saying: NullReferenceException: Object reference not set to an instance of an object.

    The line it gives me is line 108 of my PlayerController script where there is a function call to resume the game from another script (the script that controls the pause UI), but this function definitely exists. Can anybody help me with this?

    Also, most of my variables are a mess, so it may be a little hard to read.

    My Player Controller:


    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.UI;
    5.  
    6. public class OnButtonPressScript : MonoBehaviour
    7. {
    8.     public PlayerController pc;
    9.    public void QuitGame()
    10.     {
    11.         Application.Quit();
    12.         Debug.Log("QUIT GAME");
    13.        
    14.     }
    15.     public void Resume()
    16.     {
    17.         pc.playing = true;
    18.         Time.timeScale = pc.timescale;
    19.         Cursor.lockState = CursorLockMode.Locked;
    20.         gameObject.SetActive(false);
    21.     }
    22.  
    23.     public void Activate()
    24.     {
    25.         gameObject.SetActive(true);
    26.     }
    27.  
    28. }
    29.  
    My UI contol script:

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.UI;
    5.  
    6. public class OnButtonPressScript : MonoBehaviour
    7. {
    8.     public PlayerController pc;
    9.    public void QuitGame()
    10.     {
    11.         Application.Quit();
    12.         Debug.Log("QUIT GAME");
    13.        
    14.     }
    15.     public void Resume()
    16.     {
    17.         pc.playing = true;
    18.         Time.timeScale = pc.timescale;
    19.         Cursor.lockState = CursorLockMode.Locked;
    20.         gameObject.SetActive(false);
    21.     }
    22.  
    23. }
     
  2. Froggles01

    Froggles01

    Joined:
    Apr 2, 2021
    Posts:
    8
    Oops, I may have accidentally posed the same script twice, here is my player controller script:

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.UI;
    5. public class PlayerController : MonoBehaviour
    6. {
    7.     public bool playing = true;
    8.     public Transform cam;
    9.     public Rigidbody rb;
    10.     public float sensitivity = 400f;
    11.     float xrot = 0f;
    12.     Vector3 velocityz = Vector3.zero;
    13.     Vector3 velocityx = Vector3.zero;
    14.     public float speed = 50f;
    15.     private float properspeed;
    16.     public Transform raycastPart;
    17.     public float JumpPower = 50f;
    18.     public float timescale = 1f;
    19.     public OnButtonPressScript buttonpress;
    20.     // Start is called before the first frame update
    21.     void Start()
    22.     {
    23.         Cursor.lockState = CursorLockMode.Locked;
    24.     }
    25.  
    26.     // Update is called once per frame
    27.     void Update()
    28.     {
    29.         properspeed = speed;
    30.         if (Input.GetKey(KeyCode.Escape))
    31.         {
    32.             setCursorLock();
    33.         }
    34.  
    35.         if (playing)
    36.         {
    37.             if (Input.GetKey(KeyCode.LeftShift))
    38.             {
    39.                 properspeed = speed * 2;
    40.             }
    41.  
    42.             float vertical = Input.GetAxisRaw("Vertical") * properspeed * Time.fixedDeltaTime;
    43.             float horizontal = Input.GetAxisRaw("Horizontal") * properspeed * Time.fixedDeltaTime;
    44.  
    45.            
    46.  
    47.            
    48.  
    49.             if (vertical != 0f)
    50.             {
    51.                 velocityz = transform.forward * vertical;
    52.             }
    53.             if (horizontal != 0f)
    54.             {
    55.                 velocityx = transform.right * horizontal;
    56.             }
    57.  
    58.             float mousex = Input.GetAxis("Mouse X") * sensitivity * Time.deltaTime;
    59.             float mousey = Input.GetAxis("Mouse Y") * sensitivity * Time.deltaTime;
    60.  
    61.             xrot -= mousey;
    62.  
    63.             xrot = Mathf.Clamp(xrot, -90, 90);
    64.  
    65.             cam.localRotation = Quaternion.Euler(xrot, 0f, 0f);
    66.             transform.Rotate(Vector3.up * mousex);
    67.             properspeed = speed;
    68.         }
    69.     }
    70.  
    71.     void FixedUpdate()
    72.     {
    73.         RaycastHit rayInfo;
    74.  
    75.         if (Physics.Raycast(raycastPart.position, Vector3.down, out rayInfo, 0.1f))
    76.         {
    77.                 if (Input.GetKeyDown(KeyCode.Space))
    78.                 {
    79.                    
    80.                     rb.AddForce(Vector3.up * JumpPower * Time.deltaTime);
    81.                 }
    82.         }
    83.  
    84.         if (velocityz != Vector3.zero)
    85.         {
    86.             rb.MovePosition(rb.position + velocityz);
    87.            
    88.         }
    89.         if (velocityx != Vector3.zero)
    90.         {
    91.             rb.MovePosition(rb.position + velocityx);
    92.         }
    93.         velocityx = Vector3.zero;
    94.         velocityz = Vector3.zero;
    95.     }
    96.  
    97.     void setCursorLock()
    98.     {
    99.         if (playing == true)
    100.         {
    101.             playing = false;
    102.             Cursor.lockState = CursorLockMode.None;
    103.             Time.timeScale = 0f;
    104.             buttonpress.Activate();
    105.         }else if (playing == false)
    106.         {
    107.             buttonpress.Resume();
    108.         }
    109.     }
    110. }
     
  3. JoelLeeJie

    JoelLeeJie

    Joined:
    Jul 4, 2020
    Posts:
    20
    dang that's quite elaborate for a week, i've been doing it for longer but still can't do what you do haha.

    You've defined buttonpress as OnButtonPressScript, but have you actually dragged and dropped that script into your public variable?
    e.g. if your script is placed on the player, click on the player, scroll down to where the playercontroller script is, and check the variable buttonpress.

    I'm somewhat sure that when you look at your script, it'll say (none) where the buttonpress variable is.

    If it's there, like button press: (OnButtonPress) or something like that, go into play mode. Check again.

    If the script is not on your player(it shouldn't be, it should be on another gameobject like gamemanager instead of on the player), and your player dies and respawns(e.g. gets deleted before a prefab of it is spawned; because the two scripts are not on the same gameobject, the reference will be lost.

    So play your game, and before you call the function, check your variable buttonpress under the playercontroller script on the gameobject you placed it under to make sure it doesn't say (none)

    Make sure you also check that it's the correct script OnButtonPress.

    :)

    NullReferenceException basically means that you're trying to reference something you never put the reference to.
     
  4. Suddoha

    Suddoha

    Joined:
    Nov 9, 2013
    Posts:
    2,824
    Please always include the exact message which is shown in the console. It's usually better than paraphrasing what's contained in the error log, i.e. most of the time it contains the entire stack trace which includes script names, member names, lines, etc...

    Please also make sure the lines in your editor (and thus the ones mentioned in the error messages) are the same as the one in your code snippets that you add (not a big problem in this particular case as it only appears to be off by 1, but sometimes it's not as obvious at first).

    Note that the error message does not mean that a function doesn't exist (that would be an error at compile time, not a runtime error). If line 108 is actually line 107 in your post, then the only thing that could cause a NullReferenceException is an unassigned buttonPress. Make sure it's assigned on all instances that you need, or delete instances that you have added by mistake.
     
  5. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,762
    What's great about this error is that you don't have to post any code. The answer is always right at your fingertips.

    And the answer is always the same... ALWAYS. This 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.

    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.
     
  6. Froggles01

    Froggles01

    Joined:
    Apr 2, 2021
    Posts:
    8
    Thank you - I have just checked and I forgot to assign the public variable in the inspector.