I have an interesting issue. I want to player to go up to light to a different color
Hi there!
So, the other person was right, you’ll want the key press in a different function but I wouldn’t recommend OnTriggerStay. It is very inefficient and will eventually cause more problems for you than solve. This is what I’d do (this script is meant to be placed ON the button with the way I did it):
public Light pointLight;
public Color onColor = Color.green;
public Color offColor = Color.red;
private bool canBeActivated = false;
private bool isActive = false;
private Renderer rendererComp;
private void Awake() {
rendererComp = GetComponent<Renderer>();
}
void Update () {
// For testing
if (Input.GetKeyDown(KeyCode.E)) {
Activate();
}
}
// Can be called from wherever
public void Activate() {
if (canBeActivated) {
isActive = !isActive;
// State changed
if (isActive) {
ActivateButton();
}
else {
DeactivateButton();
}
}
}
private void ActivateButton() {
// Set the light color
if (pointLight)
pointLight.color = onColor;
// Change button color (directly changes material)
rendererComp.material.color = onColor;
}
private void DeactivateButton() {
// Set the light color
if (pointLight)
pointLight.color = offColor;
// Change button color (directly changes material)
rendererComp.material.color = offColor;
}
// Player has entered the area, so it can be activated
private void OnTriggerEnter(Collider other) {
if (other.tag == "Player") {
canBeActivated = true;
}
}
// Player has left the area, so it can't be activated
private void OnTriggerExit(Collider other) {
if (other.tag == "Player") {
canBeActivated = false;
}
}
I tried this and it works with setting the light color and material color. Keep in mind that you’ll want the player to have a Rigidbody so that the trigger events can be detected, and if you want the material to change rather than the color, you’ll have to adjust what I did here (like what you had hah) because I’m just modifying the color on the material. I’ll reply with a comment here after I figure out exactly why your code isn’t working.