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

Nullreference some clarification of the process please.

Discussion in 'Scripting' started by Johane, Aug 22, 2022.

  1. Johane

    Johane

    Joined:
    Jan 30, 2016
    Posts:
    19
    Hi

    So I'm trying to get my head around null references when calling from another script. In the below image the first method works fine in the first script and I can also call it from the second script but then I get a null reference i.e., firstScript.lg.enabled = false;
    So for it to work I have to (seemingly) write it as in the LampOff method. Why if "lg = GetComponent..." works in the first method do I have to point it to the light again in the second method?

    I.e., why doesn't this work?
    Code (CSharp):
    1. lg = GetComponent<Light>();
    2. lg.enabled = false;
    Am I just missing something obvious..

    Thanks

    J

    Screenshot 2022-08-22 at 17.45.23.png
     
  2. exiguous

    exiguous

    Joined:
    Nov 21, 2010
    Posts:
    1,749
    In the second method you call Light.GetComponent<Light>() which does not make much sense. So probably when you just do "lg.enabled = false" it should work when the component is there. Also it's advisable to cache "frequently" used components once in Start.
     
  3. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,713
    Using a bare GetComponent<T>() means "on this GameObject where this script is located, find me the first T (in this case a Light)"

    If these two scripts are on different objects, they BOTH need to have a light.

    It's always best to just drag references in rather than trying to be clever with GetComponent<T>()

    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
    - Identify why it is null
    - Fix that
     
  4. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,722
    It just depends on what order the methods are called in. You need to assign lg at some point before you use it. If you try to use lg before you assign it, it's not actually referencing anything, and you will get an error. Rather than assigning it in these methods as you have here, you should just assign it in Awake so you know it's guaranteed to have been assigned by the time these methods run, and you only need to assign it once. So you can remove the GetComponent calls from these methods.
     
  5. Johane

    Johane

    Joined:
    Jan 30, 2016
    Posts:
    19
    Thanks all! Very useful, much appreciated!
    I did originally assing lg to "Start" but had no luck but I will take this info and redo the script as I've clearly gone about it the wrong way.

    Thanks

    J