- Home /
Accessing function from another script won't work
I have a function in one script which i am trying to access in another script in another scene but it won't work i am getting the error "NullReferenceException: Object reference not set to an instance of an object" what am i doing wrong?
This is the function i am trying to access.
function Subtract () {
}
And this is the script i am trying to access it from.
var targetScript: EnergyScript;
targetScript = gameObject.GetComponent("EnergyScript");
function OnGUI() {
if (GUI.Button(Rect(100,100,120,40),"Level 1")){
Application.LoadLevel("leveltimetestscerne");
targetScript.Subtract(); // here i am trying to use the function
Debug.Log("live is " + targetScript.lives);
}
}
Answer by Leuthil · Mar 31, 2014 at 05:40 PM
You can't use something like gameObject.GetComponent() outside of any event function.
Put it inside of Start() or Awake().
Thanks for your respond. i have now changed it, so that the GetComponent() is in the Start function. But it is still saying the same error, can it be this line that is causing the problem ?
targetScript.Subtract();
Does this GameObject have an "EnergyScript" attached? Is it enabled? Is targetScript.lives initialized and not null?