- Home /
Light on contact
Using Unity tutorial I am making a light that turns on and off. It currently is controlled with the space bar. I want to replace the spacebar command as the control. I need to adjust the Update so that the command light turns on when GameObject Sample3 is in contact with GameObject Testbase I want the light to turn on, when contact is broken or occurs with anything else it is off. Can anyone guide me on what to put? Below is the script with spacebar as the command:
using UnityEngine; using System.Collections;
public class light : MonoBehaviour { private Light myLight;
void Start()
{
myLight = GetComponent<Light>();
}
void Update()
{
if (Input.GetKeyUp(KeyCode.Space))
{
myLight.enabled = !myLight.enabled;
}
}
}
Answer by Cornelis-de-Jager · Apr 05, 2018 at 02:02 AM
if by contact you mean touching then you can use OnTrigger events. For the code below to work you will need to have the following setup:
Your player must have the tag = 'Player'
Your object that is being touched must have a RigidBody and Be a trigger (an option ticked in rigidbody), if you don't want it to move then make it kenematic
void Start() { myLight = GetComponent<Light>(); } void OnTriggerEnter (Collider col) { if (col.tag == 'Player') myLight.enabled = true; } void OnTriggerExit (Collider col) { if (col.tag == 'Player') myLight.enabled = false; }
thanks for the help. Trigger box wasn't under rigid body it was under Box Collider. I followed that and made the following code, but it isn't causing the light to flip between active and non:
using UnityEngine; using System.Collections;
public class light : $$anonymous$$onoBehaviour { private Light myLight;
void Start()
{
myLight = GetComponent<Light>();
}
void OnTriggerEnter(Collider col)
{
if (col.tag == "Player")
myLight.enabled = true;
}
void OnTriggerExit(Collider col)
{
if (col.tag == "Player")
myLight.enabled = false;
}
}
Did you change the Tag of your GameObject Sample3 to Player?
You can use this to test:
void OnTriggerEnter(Collider col)
{
Debug.Log(col.tag+ ": On");
myLight.enabled = true;
}
void OnTriggerExit(Collider col)
{
Debug.Log(col.tag+ ": Off");
myLight.enabled = false;
}
I did rename the object. I am new, do I add that debug to a new script or replace the old?
Your answer
Follow this Question
Related Questions
Light Colision 1 Answer
Light rarely turns on 1 Answer
Using shadows as Triggers? 1 Answer
Trouble with light switch 3 Answers
Custom Collision 1 Answer