Hi.
I have made this script, that makes the character turn its flashlight on/off (Not working well yet)
public var flashlight : GameObject;
public var myLight : Light = flashlight.GetComponent("Light");
function Update()
{
if (Input.GetKey("f") )
{
myLight.enabled = !myLight.enabled;
}
}
But since I added it to my flashlight object, the console began to give me MANY errors and they were all the same : "Object reference not set to an instance of an object".
Also when I press the flashlight object from the hiearchy (dont know why, but the flashlight text is red) it stops responding and I have to turn it off.
What have I done wrong?
As Marowi said, you need to ensure your objects actually exist before using them. These changes will prevent you from using non-existent objects, but you really should either set them before running your game or in start before the execution ever gets to Update. Also like Marowi said, Input.GetKey will fire every frame the key is held down, not when it is pressed once.
public var flashlight : GameObject;
public var myLight : Light;
function Update() {
if(flashlight) {
myLight = flashlight.GetComponent("Light");
if(Input.GetKeyDown("f") && myLight) myLight.enabled = !myLight.enabled;
}
}