Hello! I am looking for a simple C# light switch script. What I mean by this is:
The player enters a trigger, and only then can the player hit a key and activate a light. I wrote this script but it did not work.
using UnityEngine;
using System.Collections;
public class Lightswitch : MonoBehaviour {
public GameObject TheLight;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
void OnTriggerEnter(Collider other)
{
if(Input.GetKeyDown(KeyCode.E))
{
TheLight.SetActive(true);
}
}
}
What have I done wrong? Did i initialize it wrong? Any help is appreciated!
OnTriggerEnter occurs only once when the object enters the trigger, and this would hardly occur at the same time that you press the key. Set a bool flag when entering the trigger, and read the key only when the flag is true:
using UnityEngine;
using System.Collections;
public class Lightswitch : MonoBehaviour {
public GameObject TheLight;
bool inTrigger = false;
void OnTriggerEnter(Collider other)
{
inTrigger = true;
}
void OnTriggerExit(Collider other)
{
inTrigger = false;
}
void Update ()
{
if(Input.GetKeyDown(KeyCode.E))
{
TheLight.SetActive(true);
}
}
}
OnTriggerEnter() is only going to be called once, the moment the player enters the collider area. You need to instead create a variable in your class, and set that variable to true when the player enters the trigger and false when they exit (using OnTriggerExit). Then, move your Input.GetKeyDown logic to Update(), first checking if that new variable is set to true.
bool inZone;
void Update() {
if (inZone) {
// Do your if (Input...) check here
}
}
Alternatively, you can move the Input.GetKeyDown logic into the OnTriggerStay() method to avoid adding the new variable (this is probably how I would do it).
Make sure your collider is a 3D collider (i.e. you aren’t using Collider2D), and make sure the “Trigger” checkbox is selected on the collider in the property inspector. Also, make sure your character has a rigidbody with collider.