- Home /
Error when accessing variables from another script: NullReferenceException: Object Reference not set to an instance of an object..
Hello people. I have 2 variables in my Flashlight script (which is located on a spotlight on the maincamera): batteryLife and maxBatteryLife. I wanted a reload type of thingy because the flashlight shuts off when batteryLife <= 0.
So i made a new script (located on the first person controller) and tried calling the two variables from Flashlight, but i get this Error: NullReferenceException: Object Reference not set to an instance of an object PickUpBatteries.ReloadCamera()
#pragma strict
function Update ()
{
if (Input.GetKeyDown("r"))
{
ReloadCamera();
}
}
function ReloadCamera ()
{
GetComponent(Flashlight).batteryLife = GetComponent(Flashlight).maxBatteryLife;
}
Can you guys help me tweak it and thell me what im doing wrong?
Answer by robertbu · Jul 10, 2014 at 02:49 PM
Your code is assuming that the 'Flashlight' component is on the same game object as the above script, but from your description it is not. The typical solution:
#pragma strict
private var fl : Flashlight;
function Start()
{
fl = GameObject.Find("Name of Flashlight Object").GetComponent(Flashlight);
}
function Update ()
{
if (Input.GetKeyDown("r"))
{
ReloadCamera();
}
}
function ReloadCamera ()
{
fl.batteryLife = fl.maxBatteryLife;
}
See these links for further information on how to use GetComponent():
http://docs.unity3d.com/412/Documentation/ScriptReference/index.Accessing_Other_Game_Objects.html
http://unitygems.com/script-interaction-tutorial-getcomponent-unityscript/
Wow thanks! It does work now and you totally explained how to syntax it properly. Thanks a BUNCH!!!
Your answer
Follow this Question
Related Questions
MonoDevelop Error 2 Answers
Find which scripts public variables appear in? 1 Answer
Slowing ground effect 2 Answers
My game wont start after i click a button 1 Answer
Error for playerPhysics 0 Answers