- Home /
Lightswitch help?
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!
Answer by DajBuzi · Feb 10, 2014 at 08:09 PM
Triggers should basicaly... triger some action so first do not let player use E key
private bool canHitE = false;
Then if he collides with your object change the "ability" to use E key
void OnTriggerEnter(Collider col){
if(!canHitE) canHitE = true;
}
void OnTriggerExit(Collider col){
if(canHitE) canHitE = false;
)
At last in Update check if user can use E key and if hes pressing it
void Update (){
if(canHitE && Input.GetKeyDown(KeyCode.E)) theLight.SetActive = true;
}
Answer by aldonaletto · Feb 10, 2014 at 08:11 PM
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);
}
}
}
Answer by supernat · Feb 10, 2014 at 08:14 PM
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.