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.
Answer by NoseKills · Jun 05, 2016 at 09:13 PM
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.