- Home /
Spotlight on/off C#
So i have a spotlight connected to the torch on my gun. and i have made the script so when i press F the flash light turns on, then when i press F again it turns off. the light turns off but it doesn't turn back on (The light is on when the game loads)
the script is attached to the spotlight. please give the answer in C#.
void Update ()
{
if (Input.GetKeyDown(KeyCode.F))
{
if (light.enabled = true)
{
light.enabled = false;
Debug.Log("light is now false");
}
if (light.enabled = false)
{
light.enabled = true;
Debug.Log("light is now true");
}
}
}
Answer by whydoidoit · Jun 30, 2012 at 08:45 AM
You need to use == signs for your tests. Currently you are setting the value in your if statements not checking it!
Well that is what is wrong with the code you posted!
void Update ()
{
if (Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.F))
{
if (light.enabled == true)
{
light.enabled = false;
Debug.Log("light is now false");
}
if (light.enabled == false)
{
light.enabled = true;
Debug.Log("light is now true");
}
}
}
Are you seeing the debug log messages?
I am getting the "light is now false" debug message, due to the light being on when you first start the game. But even if I dont use the == and just use the = the same thing happens, it just comes up with a warning in the debug log. Have you tried it yourself ingame?
I see what it is :) the second if always happens! I missed the lack of an else:
else if(light.enabled == false)
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
What is wrong with my torch script 1 Answer