I have a empty GameObject with a light. When a condition becomes true I want to activate the blinking light until the condition becomes false.
The following code works if the bool condition is true before start.
public class TestLight : MonoBehaviour
{
private Light light;
public bool flashing;
public float flashEvery = 1.0F;
public float flashDelay = 0.0F;
void Awake()
{
light = GetComponent<Light>();
}
void Start ()
{
if (flashing)
{
InvokeRepeating("FlashLight", flashDelay, flashEvery);
}
}
void FlashLight()
{
light.enabled = !light.enabled;
}
// void Update()
// {
// if (flashing) {
// InvokeRepeating("FlashLight", flashDelay, flashEvery);
// }
// }
}
I want to check for “flashing” to become true during play. So I add the Update to check for “flashing” but as you probably can tell this does not work as it makes the InvokeRepeating act strangely.
Suggestions would be appreciated.
Please not that you shouldn’t call your light variable ‘light’ as this is already an inherited member and refers to a light component which can be attached to the object. Thus, you can already this component and work with it unless you need the public Light in order to assign other lights to it.
Additionally you could test whether light is null or not in order to prevent null reference exceptions.
One simple solution is this one (enable the boolean in inspector for a quick test):