- Home /
Detect the same variable from multiple scripts
I am making a turn-based strategy game like Civilization. The solution for the turns I found is that I have a 'turnDone' variable on all my units. It is false by default, but after a step it turns true. I also have a script that is supposed to access this value from all the Units that are currently in the game.
void Update(){
GameObject[] playerUnits = GameObject.FindGameObjectsWithTag ("Player");
foreach (GameObject playerunit in playerUnits) {
if( playerunit.GetComponent<Unit>().turnDone){
playerunit.GetComponent<Unit>().turnDone = false;
}
}
}
My problem is that it looks at all the scripts individually i.e. if one unit's turnDone is true, this script will turn all the units' turnDone false. Is there a solution to access all the scripts' turnDone values collectively so that it would only turn them false if all the units' turnDone is true?
Answer by $$anonymous$$ · Jul 14, 2018 at 12:24 PM
Would this work for you?
int counter;
for (int i = 0; i < playerUnits.lentgth; i++) {
if (playerUnits[i].getComponent<Unit>).turnDone) {
counter++;
}
}
if (counter == playerUnits.length) {
// Run your code
}
Thank you very much mate! I would never have thought I should use a for loop here. It is working fine! :)
Answer by JVene · Jul 14, 2018 at 02:07 PM
This can do it:
bool isok = true;
foreach( GameObject playerunit in playerUnits )
{
if (playerUnits[i].getComponent<Unit>).turnDone == false ) isok = false;
}
if ( isok == true ) {...do your thing....}
Also, you could break out of the "isok" phase with a return, if that's appropriate, which is a quick exit - because any that aren't done should just quit.