How to have an object to react to a different object's trigger?

Hello guys.

I was wondering, how do I make a lightsoure turn off, if I interact with, say, a light switch?

Or, another example (Which is really what I’m trying to do):

My player is walking down a corridor, when, all of a sudden, the lights in the corridor should turn off by themselves.
I was thinking something a, “when the player collides which this part of the floor: turn the lights off”-script?

Any help is appreciated. :slight_smile:

Make a trigger box. tick “isTrigger” in collider options.
Then in script in a function OnTriggerEnter disable the light.
Or do you need actual code?

I thought it was something like that yeah. :slight_smile:

THanks for the advice.

Don’t forget to add some kind of check, otherwise anything that enters trigger will disable light. That’s not what you want I assume.

Actually, if you could just make a quick number of point I hav to go through to make this work
it woul dbe absolutely great. :slight_smile: If not, still, thanks so much. :wink:

That’s about it really. Here’s a code snippet in C#, don’t know if works as I haven’t tested it.
When something enters, you check for a tag(in this example) and if it matches, you turn off the light.
For a cooler effect you could make lights flicker before they turn off, but that’s unrelated.

using UnityEngine;
using System.Collections;

public class Code : MonoBehaviour {

    public Light lightToDisable;

    void OnTriggerEnter(Collider o)
    {
        if (o.tag == "Player")
        {
            lightToDisable.enabled = false;
        }
    }
}

Thanks i’ll test it shortly. :slight_smile:

As I’m working in JavaScript, I’ll have to try and translate your piece into that.

Turns out, I cant translate that into JS… I’ve not working in JS that much, so I’m gonna need some more help. :stuck_out_tongue:

public var lightToDisable : Light;
function OnTriggerEnter(Collider o)
{
	if (o.tag == "Player")
	{
		lightToDisable.enabled = false;
	}
}

Again don’t know if this will work, I normally don’t do JS

Alright, I now have this piece of code:

var lightToDisable : Light;

function OnCollisionEnter(collision : Collision) {

	if(collision.tag == "Player"){
		print("Collision!");
		lightToDisable.enabled = false;
	
	}

}

I can’t see why it doesn’t work. It seems like the problem is that there never is a collision between my player and the floor, on which this script is attached

The

print("Collision!");

never prints that there is a collision, so that might be the issue.

Any help? :slight_smile:

What is your player? If it’s not a rigidbody, it won’t return a collision.
If it’s a character controller, you would use

function OnControllerColliderHit (hit : ControllerColliderHit)

At least I think so, I don’t actually know if that would work