How to access a script from another without using GameObject.Find()

I am trying to call a function from another scrip without using GameObject.Find() to make the project more efficient. this is the function i am trying to run.

public class DoorEventHandler : MonoBehaviour {

        public static DoorEventHandler doorEventhandler;

        public delegate void GeneralEventHandler();
        public event GeneralEventHandler toggleState;
        
        public void CallEventToggleState()
        {
            if(toggleState != null)
            {
                toggleState();
            }
        }
}

The function itself does work as I can call it if I use GameObejct.Find()

I tried to call the function like this:

DoorEventHandler.doorEventhandler.CallButtonPressedEvent();

However, doing this gives me a “NullReferenceException: Object reference not set to an instance of an object”. I am not sure why this is happening as both of the scripts are in the same name spaces and are both attached to objects.

Thanks in advance for answers.

Tried doing as you suggested to no avail. I have been trying to figure this one out for quite a while and that reference to the pickup is probably debris from my desperate attempts to solve this :P

1 Answer

1

public static DoorEventHandler doorEventhandler;

is static so you can’t have assigned a value to it in the inspector. So the question is, where are you assigning a value to it before using it? If you don’t assign a value to a (reference type) variable and try to access its members, you will get a NullReferenceException. You can’t call a method through a variable that doesn’t point to an object.

If you only have one DoorEventHandler and you want the static variable to reference that DoorEventHandler, you should assign it in Awake or such. For example

public class DoorEventHandler : MonoBehaviour {
 
         public static DoorEventHandler doorEventhandler;
         void Awake(){
                doorEventhandler = this;
         }

You could Google “singleton programming” to learn more about this approach.

Each power up will be creating it's own instance of this class - what that means is that each power up will have it's own timer which will be getting destroyed :)

Would you mind marking the question as answered? :)