Search Unity

What am I missing? For each gameObject in array.

Discussion in 'Scripting' started by TheSenpaiCode, Jun 18, 2018.

  1. TheSenpaiCode

    TheSenpaiCode

    Joined:
    Jan 21, 2016
    Posts:
    50
    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.

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class LightFlicker : MonoBehaviour {
    6.  
    7.     public GameObject[] flickeringLights;
    8.  
    9.     Light lights;
    10.     public float minFlickerTime = 0.1f;
    11.     public float maxFlickerTime = 0.4f;
    12.  
    13.     void Start() {
    14.         flickeringLights = GameObject.FindGameObjectsWithTag("FlickeringLight");
    15.             for (int i = 0; i < flickeringLights.Length; i++)
    16.         {
    17.             lights = flickeringLights[i].GetComponent<Light>();
    18.             StartCoroutine(Flicker());
    19.         }    
    20.     }
    21.  
    22.     IEnumerator Flicker()
    23.     {
    24.         while (true)
    25.         {
    26.             yield return new WaitForSeconds(Random.Range(minFlickerTime, maxFlickerTime));
    27.             lights.enabled = !lights.enabled;
    28.         }
    29.     }
    30. }
     
  2. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,187
    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.
     
  3. johne5

    johne5

    Joined:
    Dec 4, 2011
    Posts:
    1,133
    it's becouse the Flicker coroutine is using lights, and lights is really just 1 object
     
  4. Trilient

    Trilient

    Joined:
    Sep 25, 2013
    Posts:
    6
    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.
     
  5. johne5

    johne5

    Joined:
    Dec 4, 2011
    Posts:
    1,133
    send the light to the coroutine

    StartCoroutine(Flicker(flickeringLights.GetComponent<Light>()));


    Code (CSharp):
    1. IEnumerator Flicker(Light light)
    2.     {
    3.         while (true)
    4.         {
    5.             yield return new WaitForSeconds(Random.Range(minFlickerTime, maxFlickerTime));
    6.             light.enabled = !light.enabled;
    7.         }
    8.     }
     
  6. TheSenpaiCode

    TheSenpaiCode

    Joined:
    Jan 21, 2016
    Posts:
    50
    Thanks, for all the help.

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