Search Unity

Question Null reference exception: an object reference is required for the non static field error

Discussion in 'Scripting' started by jtzane, Apr 19, 2021.

  1. jtzane

    jtzane

    Joined:
    Mar 18, 2021
    Posts:
    4
    Hi!
    I am new to Unity. I get this error in my first script in Desk.AddForce(10) and it doesn't perform what it should from the second script. Can you help me?
    Thanks in advance!
    Code (CSharp):
    1. public class rock_collision : MonoBehaviour
    2. {
    3.     public static Desk Desk;
    4.     public GameObject obj;
    5.     void Start()
    6.     {
    7.         obj.SetActive(false);
    8.     }
    9.     void show()
    10.     {
    11.         obj.SetActive(true);
    12.     }
    13.     private void OnTriggerEnter(Collider other)
    14.     {
    15.         if (other.gameObject.tag == "Player")
    16.         {
    17.             show();
    18.             Desk.AddForce(10);
    19.         }
    20.     }
    21. }
    22.  
    Code (CSharp):
    1. public class Desk: MonoBehaviour
    2. {
    3.     public void AddForce(int damage)
    4.     {
    5.        GetComponent<Rigidbody>().AddForce(Vector3.up * damage, ForceMode.VelocityChange);
    6.     }
    7.  
    8. }
     
  2. chengwang2077

    chengwang2077

    Joined:
    Nov 23, 2019
    Posts:
    131
    Your desk field is not initialized, it is null
     
  3. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,745
    Null reference DOES NOT require a forum post, ever. Why?

    Because the answer is always the same... ALWAYS. It is the single most common error ever. It's less than a typo.

    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.