Code is working, but still giving a NullReferenceException

Hello! I know this is a bit of a weird question, because my code actually works as I want it to. HOWEVER, each time I press Play in Unity, it keeps giving me NullReferenceException.
My problem is that I’m afraid that if I keep it as it, it’s going to snowball into some other problem or even create a bug. Plus, I want to understand why this error occurs in the first place (I’m very new to C# and Unity).

Idea behind the code:
Two Scripts.

  1. LightTrigger - is supposed to change its bool value isTriggered to true when the player collides with the Game Object it’s attached to.
  2. LightFlickerTriggered- is the Light script, that emits the light, but makes the light flicker when the bool (isTriggered) from the first script (LightTrigger) is set to true.

LightTrigger script:

public class LightTrigger : MonoBehaviour
{
    public bool isTriggered;

    void Start()
    {
        isTriggered = false;
    }
    
    void OnTriggerEnter2D(Collider2D other)
    {
        isTriggered = true;
    }
}

LightFlickerTriggered script (I ommited all the lines of code related to other things):

public LightTrigger lightTrigger;

 void Update()
 {
     timer += Time.deltaTime;

     if (timer > interval && lightTrigger.isTriggered)
     {
         ToggleLight(); *//------ function that starts the flickering sequence*
     }
 }

In the Unity project itself I dragged the LightTrigger script to the lightTrigger window on my light source.

The code works. The light shines as usual until the player actually walks over the trigger, and then it starts and keeps on flickering.

But…
the NullReferenceException (Object reference not set to an instance of an object) still keeps appearing in the log. And it is guiding me to this line in LightFlickerTriggered script:

if (timer > interval && lightTrigger.isTriggered)

Is there anyway I can solve this?

Thank you in advance.

1 Answer

1

that could be caused by another LightFlickerTriggered script in your hierarchy that you did not asign a lightTrigger to.

I think this is true for all errors that come from your scripts:

if you click on the error in the Console window the object that’s causing the issue will be highlighted for a short time
v
image


also you could turn on the errorPause option on the Console window in case you want Unity to pause the game for you every time an error occurs

Thank you so much, I will give it a try once I’m at the pc and recheck if I have the script attached to any other object (though it shouldn’t be, but hopefully this highlighting trick will help me!!).

–

I just checked AND YOU WERE COMPLETELY RIGHT!!! I forgot I put the script on another light as well. THANK YOU SO MUCH!

–