- Home /
Turning a Light on With Collision Detection
I am trying to write a script whereby when a cube lands on the floor the light turns on. I am working in C#, not in Javascript.
public class lighton : MonoBehaviour {
void OnCollisionEnter (Collision myCollision) {
Light myLight = gameObject.Find("Light").AddComponent(Light);
myLight.enabled = true;
myLight.intensity = 5;
}
}
I get an error that says:
Static member `UnityEngine.GameObject.Find(string)' cannot be accessed with an instance reference, qualify it with a type name instead
Any input is appreciated
Answer by fafase · Jun 14, 2012 at 06:12 AM
OK I removed my former answer, my bad I got mixed up between Js and C#
public class lighton : MonoBehaviour {
public Light myLight;
void Start () {
GameObject light = GameObject.FindWithTag("Light");
myLight = light.GetComponent<Light>();
myLight.enabled = false;
}
void Update () {
if(Input.GetKeyDown(KeyCode.Space))
myLight.enabled = !myLight.enabled;
}
}
It works for me, I can switch my light on and off. All you need now is to convert it into a collision as I am using a button to switch.
Thank you very much kind person :-) It's working. Below is my final code I used to get a light turn on as soon as a cube collided with something.
public class lighton : $$anonymous$$onoBehaviour {
public Light myLight;
void OnCollisionEnter (Collision myCollision) {
GameObject light = GameObject.FindWithTag("Light");
myLight = light.GetComponent<Light>();
myLight.enabled = true;
}
}
*(A note to everyone)Remember to rename the tag on your light source to "Light" if you're using this example.
You are great Latsushi ! I have been looking for this syntax for more than one week - to turn on the light "OnCollisionEnter". Many thanks
If your collision happens once in a while, this code is fine, on the other hand if it is likely to happen many times you should cache reference you variable.Lookup functions are expensive and it is better to avoid them. See what I have done in the Start function.
Your answer
![](https://koobas.hobune.stream/wayback/20220613072743im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Using OnCollisionEnter with cube 2 Answers
Don't understand why this on collision script doesn't work. 2 Answers
How to find a Class by value 2 Answers