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 Error "object reference not set to an instance of an object unity"

Discussion in 'Scripting' started by harrisonpops7, Aug 20, 2023.

  1. harrisonpops7

    harrisonpops7

    Joined:
    Aug 19, 2023
    Posts:
    1
    Im getting the Error "object reference not set to an instance of an object unity" when the script is exicuted I dont know how to fix

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class Detectors : MonoBehaviour
    6. {
    7.     public Score logic;
    8.     void Start()
    9.     {
    10.         logic = GameObject.FindGameObjectWithTag("bean").GetComponent<Score>();
    11.     }
    12.  
    13.     void OnTriggerEnter(Collider other)
    14.     {
    15.         logic.addScore();
    16.     }
    17. }
    18.  
    on line 15 it has the problem
     
  2. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,140
    Null ref errors or Object ref not set to an instance

    1. Find out what is null
    2. Find out why it's null
    3. Fix it.

    The value of logic is null.
     
    Kurt-Dekker and wideeyenow_unity like this.
  3. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,561
    Don't write code like this. It causes null references.

    Keep in mind that using GetComponent<T>() and its kin (in Children, in Parent, plural, etc) to try and tease out Components at runtime is definitely deep into super-duper-uber-crazy-Ninja advanced stuff.

    This sort of coding is to be avoided at all costs unless you know exactly what you are doing.

    If you run into an issue with any of these calls, start with the documentation to understand why.

    There is a clear set of extremely-well-defined conditions required for each of these calls to work, as well as definitions of what will and will not be returned.

    In the case of collections of Components, the order will NEVER be guaranteed, even if you happen to notice it is always in a particular order on your machine.

    It is ALWAYS better to go The Unity Way(tm) and make dedicated public fields and drag in the references you want.

    And as Brath already posted, the answer is always the same... ALWAYS!

    How to fix a NullReferenceException error

    https://forum.unity.com/threads/how-to-fix-a-nullreferenceexception-error.1230297/

    Three steps to success:
    - Identify what is null <-- any other action taken before this step is WASTED TIME
    - Identify why it is null
    - Fix that
     
  4. xucian

    xucian

    Joined:
    Mar 7, 2016
    Posts:
    755
    Statistically, there's no Score component on the "bean" object. Check its inspector.