The first recommendation I have is putting those inner conditional statements into one statement. If they both start with check the Fire1 button, that’s good enough, then when you’ve confirmed that, just flip the state of the light. “OnOff” is a confusing variable name, if you think of it as a bool, then you have “OnOff” is true or false whereas just saying “On” as true or false is more intuitive.
Those aside, what is the error given to you? Are you properly setting the lightPrefab?
I’m shocked at how forgiving JavaScript/UnityScript is on types, it makes it harder for me to read.
I do not really have an error. In game I have a flashlight with a light attached to it (var lightPrefab : Light;). I dropped the light onto that in the editor.
When I go ingame, I press left mouse and the light disappears, and when I press the LBM again nothing happens when the light should show itself again.
Here is the problem, your “else if” is ignored, because the first if catches it. Then the first if goes into its inner conditional, which says “if the light is on, turn it off”. You might never reach the inner conditional for else if.
When you do an if/elseif/else they are exclusive, the first conditional to match is executed, then the rest are ignored.
private var IsOn : Boolean = true;
function Update ()
{
if (Input.GetButtonDown ("Fire1"))
{
IsOn = !IsOn; //flips it between true/false
lightPrefab.light.intensity = IsOn ? 1 : 0; //if IsOn is true, uses "1", otherwise if it's false, use "0"
}
}
EDIT: damn you JRavey! Good explanation.
EDIT: lol, and rizn. Serves me right for watching Daily Show at the same time and taking my time writing this
I guess if you needed to keep the light enabled for other reasons, it could just be:
lightPrefab.light.intensity = (lightPrefab.light.intensity == 1) ? 0 : 1;