What am I missing? For each gameObject in array.

Hello,

I’m trying to make all the lights with a certain tag flicker. So far only one of the lights is currently flickering. Any idea what I’m missing? They all say active.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class LightFlicker : MonoBehaviour {

    public GameObject[] flickeringLights;

    Light lights;
    public float minFlickerTime = 0.1f;
    public float maxFlickerTime = 0.4f;

    void Start() {
        flickeringLights = GameObject.FindGameObjectsWithTag("FlickeringLight");
            for (int i = 0; i < flickeringLights.Length; i++)
        {
            lights = flickeringLights[i].GetComponent<Light>();
            StartCoroutine(Flicker());
        }     
    }

    IEnumerator Flicker()
    {
        while (true)
        {
            yield return new WaitForSeconds(Random.Range(minFlickerTime, maxFlickerTime));
            lights.enabled = !lights.enabled;
        }
    }
}

Well, your coroutine is changing what light it targets. Each time your loop hits, you’re getting the light component and assigning that to lights, which overwrites the previous lights value. So the last one in the list should be the only one that flickers.

it’s becouse the Flicker coroutine is using lights, and lights is really just 1 object

Looks to me like you need an array of lights as well, you currently only have one light you’re accessing. You change it’s value at the start as your for loop iterates through your array of gameobjects.

send the light to the coroutine

StartCoroutine(Flicker(flickeringLights*.GetComponent()));*
csharp* *IEnumerator Flicker(Light light) { while (true) { yield return new WaitForSeconds(Random.Range(minFlickerTime, maxFlickerTime)); light.enabled = !light.enabled; } }* *

Thanks, for all the help.

“Flicker(Light lights)” got it to work it. Forgot all about doing something like that.