hi guys, could you help me figure out what’s wrong with this script I did to turn the light off and on? I don’t understand why it doesn’t work …
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TurnLight : MonoBehaviour {
public GameObject light;
private bool on = false;
void OnTriggerStay(Collider other) {
if (other.tag == "Player" && Input.GetKey(KeyCode.E) && !on)
{
light.SetActive(true);
on = true;
}
else if (other.tag == "Player" && Input.GetKey(KeyCode.E) && on)
{
light.SetActive(false);
on = false;
}
}
}
just to make it clear as we cant see the scene…
you do stand INSIDE a collider
that has this script attached
your player object that has the player tag (not a child or parent)
is the same object as the one having the collider (not a child or parent)
the collider is marked as trigger
the light gameobject is the same object that has the light attached (not a child or a parent)
the code looks fine to me so other than the ontriggerstay being unreliable, i would look for the flaw outside of the code…
did you debug it and was the ontriggerstay ever called?
add a breakpoint to the code at the first if, run the code from VS and check the content of the variables with hoovering the mouse over
2 Likes
One thing is not clear to me … I have created a sphere object, then right click on the sphere and create a point light … at this point the script and the sphere collider must be added to the point light or to the sphere?
I tried to put it on a single point apart and it works, but in the middle … it turns off the light but then doesn’t turn it back on …
Is it calling “light.SetActive(true)”? Add Debug.Log statements everywhere to find out what is going on.