- Home /
NullReference when calling a function to another script
Surely is gonna be a stupid thing to fix, but i'm blind right now and can't see where is the problem.
Basicly I'm trying to call a function from a script to another. The function is called from an object that have a singleton in it, he other is just a normal public function.
This is the code snippet to call the function:
PlayerFlashlight flashlight;
void Start() {
PlayerFlashlight flashlight = GetComponent("PlayerFlashlight") as PlayerFlashlight;
}
void OnGUI () {
if(displayInventory){
if(GUI.Button(new Rect(10, Screen.height - 110, 50, 50), "<@"))
flashlight.ApplyBattery ();
}
}
}
And here the function called
public void ApplyBattery () {
if(batteryCount > 0)
{
if( batteryCharge >= 100 )
{
Debug.Log("Fully charged already");
}
else
{
batteryCharge = 100;
batteryCount -= 1;
}
}
else
{
Debug.Log ("No batteries left");
}
}
I'm getting a NullReference whenever I click the gui button, and the error point to flashlight.ApplyBattery();
Whats wrong?
Answer by Bulgroz · Aug 11, 2012 at 06:11 PM
The easiest is to define a flashlight gameobject in the calling script and then assign the gameobject w the other script attached to it to that Gameobject via the inspector (drag from the Projrct hierachy to the inspector of the calling scripts parent object
Then make a local variable "fl" of the scripttype type and assign the referenced script via the gameobject.GetComponent tecnique to that
Then call the function as fl.ApplyBattery();
Good luck
/Chris
Thanks for your help, I've menaged to get it working, I used a public static method.
Answer by Bulgroz · Aug 11, 2012 at 12:31 AM
Use references to access methods in other objects' scripts using the GetComponent methos
( see http://docs.unity3d.com/Documentation/ScriptReference/index.Accessing_Other_Game_Objects.html )
Aternatively, in C# you can define your method as Static, to allow direct calling it from another script.
/Chris
Still doesn't work, should I instantiate the script with the function to call maybe?