Stop coroutine not working

Hi - I need a light to be on for 2 seconds and then be set to active = false each time a camera is set to active, but instead the camera starts flashing continuously, I guess because the coroutine is looping?

Do you know what I’m doing wrong?

var light1 : GameObject;
var cameraF4N : GameObject;

function Update () {

if(cameraF4N.activeInHierarchy == true) {

StartCoroutine ("spotLightCoroutine");

}

if(cameraF4N.activeInHierarchy == false) {

StopCoroutine ("spotLightCoroutine");

}

}

function spotLightCoroutine () {

while (true) {

light1.active = true;

yield WaitForSeconds (3);

light1.active = false;

yield;

}

}

All the best, Laurien

1 Answer

1

You should assign your script to the “cameraF4N” gameobject and use the OnEnable and OnDisable functions. The problem is that you’re starting a lot of coroutines in the update function, which is called every frame.

var light1 : GameObject;

function OnEnable()
{
    StartCoroutine ("spotLightCoroutine");
}

function OnDisable()
{
    StopCoroutine ("spotLightCoroutine");
}

function spotLightCoroutine ()
{
    light1.active = true;
    yield WaitForSeconds (3);
    light1.active = false;
}

If attaching the script to the “cameraF4N” gameobject is not an option, then you could use a bool flag to make sure you only start the coroutine once.

var isRunning : boolean

function Update () 
{
    if(cameraF4N.activeInHierarchy == true && !isRunning) 
    {
        StartCoroutine ("spotLightCoroutine");
    }
    else if(cameraF4N.activeInHierarchy == false) 
    {
        StopCoroutine ("spotLightCoroutine");
        isRunning = false;
    }
}

function spotLightCoroutine ()
{
    isRunning = true;
    light1.active = true;
    yield WaitForSeconds (3);
    light1.active = false;
    isRunning = false;
}

Yay thank you so much!!! (I didn't think of assigning it to the camera instead :/ - that solves a lot of other scripting problems I'm having. How silly) :)