0
\$\begingroup\$

I have this code that counts how many GameObjects (crops) in the scene

GameObject[] crops;

and the code to get the health component of each crops

    Health[] health;
    crops = GameObject.FindGameObjectsWithTag("Crop");
    health = new Health[crops.Length];
    for (int i = 0; i < crops.Length; i++)
    {
        health[i] = crops[i].GetComponent<Health>();         
    }

I can now access the state of these crops using

    health[i].Invulnerable //this is a bool from the Health.cs script

now I want to count the crops that are Vulnerable and Invulnerable. How can I achieve that? Thanks!

\$\endgroup\$
2
\$\begingroup\$

Is there something wrong with a simple for loop?

int vulnerable = 0;
int invulnerable = 0;
for (int i = 0; i < health.Length; ++i) {
    if (health[i].Invulnerable) {
        invulnerable++;
    }
    else {
        vulnerable++;
    }
}
\$\endgroup\$
2
\$\begingroup\$

Alternatively, you can use the Linq lambda like so:

GameObject[] crops;
int invulnerable_count = 0;
int vulnerable_count = 0;

public void your_function(){
    if(crops != null){
        //List has plenty of nice iteration functions
        invulnerable_count = crops.ToList().Where(crop => isInvulnerable(crop)).Count;
        //since Invulnerable is a boolean, you can subtract to get the complement
        vulnerable_count = crops.Length - invulnerable_count;
    }
}

private boolean isInvulnerable(GameObject crop){
    Health health = crop.GetComponent<Health>();
    return health != null && health.Invulnerable;
}
\$\endgroup\$
0
\$\begingroup\$

your code is right but as you may know its not opptimized and not the best approach. if the scene is so big finding objects by tag or even layer can be time consuming an heavy even with unity new approach on searching objects.try to add your corps objects to a list in a manager or any singleton class when they are instantiated then just find your corps from that list. it can be much faster and no hiccups.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.