- Home /
Light rarely turns on
I've got a trigger box, which is the region of the light switch. However, this only works sometimes for some odd reason.
using UnityEngine; using System.Collections;
public class TriggerTest : MonoBehaviour {
private Light myLight;
private void Start()
{
myLight = GetComponent<Light> ();
}
void OnTriggerEnter (Collider other)
{
if (Input.GetKey(KeyCode.F))
{
myLight.enabled = true;
}
if (Input.GetKey (KeyCode.G))
{
myLight.enabled = false;
}
}
}
Answer by allenallenallen · May 23, 2017 at 11:01 AM
Currently, you have to press and hold F and then approach the Trigger to turn on the lights. OnTriggerEnter only runs once when you enter the trigger. You are limited to only that single frame to interact with the lights. After that, you would have to leave and enter the Trigger again to interact with the lights again.
I assume the Trigger is like an area where you can interact with the switch. In which case, it's probably better to use OnTriggerStay(). This means as long as you are in the Trigger, you can press F and G to interact with the lights.
https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnTriggerStay.html
Would you know how I could adapt this code to make the "F" turn light on and off? Also rather than having a local light, how could I link a public one to it?
Thank you so much for your answer also! I didn't know there was a such function as "OnTriggerStay"!!
Change
myLight.enabled = true;
to
myLight.enabled = !myLight.enabled;
This will toggle.
What do you mean by a local or public light? Do you mean the variable should be public? Then just change the word private to public. As long as the light exists in the scene, there's a way to link it.
Thank you so much! It works perfectly! If you're wondering, I'm creating a voice recognition game for my project, but I'm also implementing normal mechanics too~~
using UnityEngine; using System.Collections;
public class Switch : $$anonymous$$onoBehaviour {
public Light myLight;
public Camera myCamera;
void Start ()
{
Light myLight = GetComponent<Light> ();
Camera myCamera = GetComponent<Camera> ();
}
void OnTriggerStay (Collider other)
{
if (Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.F))
{
myLight.enabled = !myLight.enabled;
}
if (Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.E))
{
myCamera.enabled = !myCamera.enabled;
}
}
}
Your answer
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
Detecting collisions 3 Answers