- Home /
How to switch off two lights?
Hello UnityAnswers,
I am a beginner at Unity and want to switch off the headlights of a car. Therefor I created two spot lights and linked them. Actually, I don't know if this is linking or if this is childing?
In my JavaScript-File I have defined a variable, like this:
var lightToToggle : GameObject;
Clicking on a button calls the function which performs follwing:
function OnMouseDown(){
if(lightToToggle.light.enabled){
lightToToggle.light.enabled = false;
}
else{
lightToToggle.light.enabled = true;
}
}
Unfortunately only the (blue marked) headlight goes on and off. Do I have to access the children (if this is a parent-child-situation). And if so, how do I get the child?
Any help is appreciated!
Greetz Chris
Answer by Griffo · Nov 24, 2012 at 06:03 PM
There might be a better way but you could do this -
private var rightLight : Light;
private var leftLight : Light;
private var LightR : GameObject;
private var LightL : GameObject;
function Awake(){
LightR = GameObject.Find("Right Light"); // Find the gameObject with the Right Light
LightL = GameObject.Find("Left Light"); // Find the gameObject with the Left Light
rightLight = LightR.GetComponent(Light);
leftLight = LightL.GetComponent(Light);
}
function Update{
function OnMouseDown(){
if(rightLight.enabled){
rightLight.enabled = false;
rightLight.enabled = false;
}
else{
rightLight.enabled = true;
rightLight.enabled = true;
}
}
}
@Giffro: Thank you for your answer it works :). Do I need to put On$$anonymous$$ouseDown() in the Update function?
Answer by greatestprez · Nov 24, 2012 at 06:20 PM
This should work:
function OnMouseDown(){
if(lightToToggle.light.enabled){
lightToToggle.light.enabled = false;
lightToToggle.transform.FindChild("Headlight").light.enabled = false;
}
else{
lightToToggle.light.enabled = true;
lightToToggle.transform.FindChild("Headlight").light.enabled = true;
}
}
Thank you greatestprez for your answer. Your Code is short and works fine for the given issue. You are using FindChild() therefor I assume that we have a parent-child situation?
Your answer
Follow this Question
Related Questions
Can someone help me fix my Javascript for Flickering Light? 6 Answers
Setting Scroll View Width GUILayout 1 Answer
Help With "Scripting" 1 Answer
Help with selecting and deselecting an object? 1 Answer
Overlap Detection HELP!! 0 Answers