I am using C# to make a spot light attached to the main camera on the firstpersoncontroller turn off and on again with the same key pressed, but it isn’t working. I found out that the Update function goes up until the G key is pressed, when the flashlight turns off, but then stops and doesn’t start again, not even registering any further G key presses. Could somebody tell me why it isn’t working, and how to fix it?
using UnityEngine;
using System.Collections;
public class Flashlightcontrol : MonoBehaviour {
public Light Flashlight;
private bool LightEnabled = true;
void Update()
{
if(Input.GetKey(KeyCode.G))
{
LightEnabled = !LightEnabled;
Flashlight.active = LightEnabled;
}
}
}
active is a GameObject property. If you set Flashlight.active to false, Unity actually does Flashlight.gameObject.active = false, deactivating the game object to which the light belongs, and the scripts attached to it simply stop executing (I bet that the script above is attached to this object…)
EDITED: Also change GetKey to GetKeyDown, as @TheDarkVoid said
Make sure you do not place this script on the light GameObject; any other will do.
using UnityEngine;
using System.Collections;
public class ScriptFlashlight : MonoBehaviour
{
public Light myLight;// the light to be triggered (on and off)
public bool lightEnabled = true;// if the light is enabled or disabled
// Use this for initialization
void Start ()
{
Debug.Log ( "The light started on!" );
}
// Update is called once per frame
void Update ()
{
// check if the 'F' key was pressed
if ( Input.GetKeyDown ( KeyCode.F ) )
{
lightEnabled = !lightEnabled;// toggle the boolean value (this will initially be false)
myLight.enabled = lightEnabled;// enable or disable the light based on the boolean value
// this is just for testing and debug purposes
// check if the light is enabled
if ( lightEnabled )
{
Debug.Log ( "Light turned on..." );
}
else
{
Debug.Log ( "Light turned off..." );
}
}
}
}