- Home /
How do I change gameObject values in an array all at once?
I made an array that gets all the gameobjects with a specific tag and then I put a foreach loop that changes a value for them, I also put a timer on it because I want the values to slowly rise. The problem is that once the first gameobject in the array reaches the limit it moves on to the next, while I want it to change the values all at once instead of changing them one by one. I have also tried the for i loop and it does the same exact thing. Here's the code for further information.
private float Timer = 1; private int maxtroops = 30; [SerializeField] float MaxTimer; [SerializeField] GameObject[] Planets; void Start() { Planets = GameObject.FindGameObjectsWithTag("Planet"); } void Update() { Timer -= Time.deltaTime; foreach(GameObject planet in Planets){ if(Timer < 0 && planet.GetComponent<Value>().troops < maxtroops){ planet.GetComponent<Value>().troops++; Timer = MaxTimer; } } }
Answer by Magso · Jun 08, 2020 at 12:18 AM
This is happening because you reset the timer in the foreach, it resets then all the other iterations are ignored because Timer < 0
is false. Once Planets[0]
has had it's value set to maxtroops
, now the first iteration gets ignored because planet.GetComponent<Value>().troops < maxtroops
is now false but Timer < 0
remains true so the same thing happens to the second iteration and so on and so forth.
An easy way to fix this would be to put Timer = MaxTimer;
after the foreach loop or have if(Timer == MaxTimer)
start the for loop.