Ok so what im trying to do is get a light to turn on and off every2 seconds. It turns off the first time just fine then it starts to rapidly flicker on and off. I dont know what I did wrong here. This script is attached to a point light.
public class StrobeLight : MonoBehaviour {
bool lightOn;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
StartCoroutine(turnLightOn());
}
IEnumerator turnLightOn()
{
yield return new WaitForSeconds(2);
if(lightOn)
{
this.light.enabled = false;
lightOn = false;
}else
{
this.light.enabled = true;
lightOn = true;
}
}
}
Thanks for any help with this.
put a yield new WaitForSeconds(2) commands after the line 28
Update is being called each frame. You are stacking these yields up 30-n times based off frame rate, this isn’t a single call. You need to put a condition on the coroutine(or don’t use it at all) that observes the amount of time past, if it is say greater then 2 seconds, have it do the flicker and in that case you will not need a coroutine at all.
public class StrobeLight : MonoBehaviour
{
public float flickerDelay = 2.0f;
bool lightOn;
private float flickerTimePassed = 0.0f;
// Update is called once per frame
void Update ()
{
if (flickerTimePassed >= flickerDelay)
{
flickerTimePassed = 0.0f; // reset the time since last on off.
turnLightOnOff();
}
else
{
flickerTimePassed += Time.deltaTime;
}
}
void turnLightOnOff()
{
if(lightOn)
{
this.light.enabled = false;
lightOn = false;
} else {
this.light.enabled = true;
lightOn = true;
}
}
}
Starting a new coroutine each frame, means that you are having a bunch of coroutines statcking up. By the time you reach 2 seconds you will have somewhere around 30 to 60 going. Here is a bit of code to do what I think you want to do…just a single coroutine. Change the wait time to make it flicker faster.
public class StrobeLight : MonoBehaviour {
bool lightOn;
void Start () {
lightOn = this.light.enabled;
StartCoroutine(turnLightOn());
}
IEnumerator turnLightOn()
{
while(true) {
yield return new WaitForSeconds(2);
lightOn = !lightOn;
this.light.enabled = lightOn;
}
}
}