Getting this error when trying to access another script. C#

NullReferenceException: Object reference not set to an instance of an object

I’m trying to access my script doors.cs so I have this set up

    public doors d;

then later in the update:

if (d.redKey == true){//red key is a bool from the doors script

But it keeps pointing to this line saying:

NullReferenceException: Object reference not set to an instance of an object




I can’t find this to work for me and people keep giving lengthy complicated explanations or just a useless link to what I’m not looking for. This is what I want to do:

I have a doors.cs script. In this script there is there is a boolean that becomes true when the player hits a red key. It is called “aredKey”

Now from here in my other script I wan’t to access this boolean. Basically the script would say if the doors.cs script’s boolean aredKey is set to true, then Debug.Log(“Test”)

Simple right? I hope so. Thanks

This is one of the most common issues on this list. Both scripts need to be attached to game objects. Then you need to drage the doors game object (the one with the doors script on it) to the doors variable in whatever game object the script above is attached to. You cannot drag the script to the game object. You need an instance of that script, so you have to drag the game object it is attached to.

You can also make redKey variable is public static in door script so you can access it without creates instance of door as d

Well you should put an instance of the doors script in variable d as others said. If it’s attached to the same gameObject then
void Awake()
d = GetComonent();

If the script is attached to another gameObject then either drag that gameObject to d in inspector or find that gameObject in code using FindObjectsOfType or GAmeObject.Find and then GetComponent the doors script.

It’s standard practice to write Doors for type name instead of doors also.