- Home /
How to get array of objects of type "Script" and with variable with value "X"?
I used:
foreach (EnemyHealth botCount in hazardCount) {
if (hazardCount.myTeam == GetComponent<BaseDomain>().myTeam) {
if (botCount.GetComponents<EnemyHealth>().Length >= hazardMax) {
StopCoroutine(spawnWaveCoroutine);
}
a = botCount.GetComponents<EnemyHealth>().Length;
}
}
but "a" returns only one of the array, I need all of objects with script "EnemyHealth" and with team variable equals the respective base team.
Answer by ooblii · Sep 03, 2017 at 04:53 PM
Are you just trying to count something, and stop spawning once the loop has reached that number, or are you going to work with the EnemyHealth class?
"a" is only ever going to be an array of however many EnemyHealth scripts you have on the last botCount which satisfies the first condition in your foreach loop.
You could try using FindObjectsOfType. But the way you have it set up, it would probably return elements on both teams.
Why not before you run the loop, declare a List of < EnemyHealth> and when your condition is satisfied, call:
enemyHealthList.Add(botCount);
If you're simply trying to stop spawning once you've reached hazardMax, a for loop is probably better suited than a foreach.
Hi, thanks for the help:
hazardCount = GameObject.FindObjectsOfType<EnemyHealth>();
foreach (EnemyHealth botCount in hazardCount) {
if (botCount.myTeam == GetComponent<BaseDomain>().myTeam) {
List<EnemyHealth> enemyHealthList = new List<EnemyHealth>();
enemyHealthList.Add(botCount);
if (enemyHealthList.Count >= hazard$$anonymous$$ax) {
StopCoroutine(spawnWaveCoroutine);
}
myHazards = enemyHealthList.ToArray();
}
}
Two bots per wave are spawned, myHazards(I removed "a") array is returning only one item again
List<EnemyHealth> enemyHealthList = new List<EnemyHealth>();
Should be declared before you start the loop. Right now you're just making a new List every time you satisfy the condition.
myHazards = enemyHealthList.ToArray();
should also be outside the loop as you're just converting a List with a single item to an Array with a single item, and it's always going to be the same.
Just curious, what explicitly are you trying to accomplish? There is some redundancy in the code that could be worked out. Why do you need a myHazards Array when you already have an enemyHealthList?
I got it! Thank you very much, myHazards is just for I see what's happening in the inspector. Can you see my game? :P https://youtu.be/rEIk$$anonymous$$bI8w4g
Your answer
![](https://koobas.hobune.stream/wayback/20220612134117im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How do I compare the position of my player to each elements position of an array of GameObjects? 0 Answers
Array problems 3 Answers
Definition problem 1 Answer
How do I find a local variables index in a foreach loop? 1 Answer
I have an array of players. How can I get my enemy to go to the closest one? 0 Answers