NullReferenceException- Object reference not set to an instance (Door with Key)

Hi folks,

I’m having the hardest time trying to figure out why line 268 keeps coming up with a null reference exception…
Line 262 works
Line 264 does a check and it works
Line 266 verifies its correct
Line 267 copies the script from the object
Line 268 Does not work at all …

The gameobject Door has the MasterDoorController script which is used to open all doors one at a time on a OnCollisionEnter trigger on each door within the scene.

Because this script is used on all doors, locked and un-locked, I just need to look for the Red door and make a copy of it (GameObject m_door_R = GameObject.FindWithTag(“LockedDoor_R”)

If it is the red door (m_door_R.CompareTag(“LockedDoor_R”) and I have the red key (SaveScript.HaveKey_Red) unlock the door.

In the MasterDoorController script there is a public method that sets the “Lock(true)” to false, making the door available to open

The issue is I can’t seem to figure out how to do that without getting the NullReferenceException error

I know this may seem simple to some of you, but it sure is kicking my butt…

Any help would be greatly appreciated!

I’m guessing you’re getting a false positive - an object that has the LockedDoor_R tag (maybe erroneously) but does not have the MasterDoorController script attached. Try adding this extra parameter to your Debug.Log:

Debug.Log("Red Door Locked: " + m_door_R.tag, m_door_R);

Then click on your debug message and look at the object you see - it’s probably not one that has MasterDoorController.

The simple fact is that your GameObject tagged with “LockedDoor_R” does not have a MasterDoorController component attached to it.

If you disagree with that, can you share some screenshots of your Hierarchy? Especially the inspector for the GameObject tagged with “LockedDoor_R” and showing the MasterDoorController component on it?

GameObject.FindWithTag returns the first game object it can find with the specified tag.
So if you have multiple GameObjects with the same LockedDoor_R tag in the scene, it might return the wrong one that you didn’t expect to return.

1 Like

There is only one gameobject with LockedDoor_R tag in the scene

Tried this… this was the result
6215276--683252--upload_2020-8-17_12-40-16.png

Here is a screen grab of my inspector
6215276--683255--upload_2020-8-17_12-41-45.png

Hi All,

Thanks for your help, but I solved it… You guys were right in your assumptions, I had duplicated the red door, weeks ago, but forgot to disable it (very large scene), so the code was seeing two doors with the same tag… hence the null exception crash… damn, I thought I was doing everything right in my code, as it turns out I was… just a conflicting duplicate tag… disabled the duplicate and tada… ahhh lesson learned

1 Like

No worries. Sometimes you’re in too deep and it takes a fresh set of eyes to question all your assumptions.

1 Like