- Home /
Light connected to boolean doesnt switch
Hey, like many I'm new so please no hate
So I'm currently working on a school project, building a completely working car with unity. Therefor I need a blinker as well, which I'm currently trying to implement, but I ran into the problem, that when I start the game, the Blinker is on, I manage to switch it off, but I can't get it to go on again. I checked, and the boolean, which should control the light, doesn't switch to true in the first place. Code:
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class BlinkerScript : MonoBehaviour {
[SerializeField]
private bool lightsOnL;
void Start ()
{
lightsOnL = true;
}
void Update ()
{
if (Input.GetKeyDown(KeyCode.Q))
ToggleBlinkerL();
}
void ToggleBlinkerL()
{
if (lightsOnL == false)
{
this.GetComponent<Light>().enabled = true;
lightsOnL = true;
}
if (lightsOnL == true)
{
this.GetComponent<Light>().enabled = false;
lightsOnL = false;
}
}
}
Answer by PizzaPie · Jan 13, 2018 at 07:15 PM
Change line 22 to
else if (lightsOnL == true)
Here's what is going wrong
Game starts lightsOnL = true and light component is enabled
Input happens lightsOnL = true so first if is skipped, second if is executed, light is disabled, lightsOnL =false
Input happens lightsOnL = false so first if executed, light is enabled and lightsOnL = true, now second if is executed too thought (here's the problem) so light is disabled again and lightsOnL =false again on same frame.
Same as above for infinite times of input events
You could also simplify it as
Light light;
void Start{
light = this.GetComponent<Light>(); //cache it so you don't have to look for it every time
}
void ToggleBlinkerL()
{
light.enabled = !light.enabled; //changes enabled state to its different state regarding current state
}
Cheers!
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
GetComponent, set boolean to true but it willn't revert 3 Answers
NetworkAnimator: SetBool vs. SetTrigget? 1 Answer
How to Set Application.isFocused? 1 Answer