Foreach loop is affecting all objects even if they don;t meet the if statement requirements.

In the below code I wanted the foreach loop to see what the quality score was on each plant and if its higher than a certain value a star is added and or the text displayed above is changed. only one of these plants meets that criteria but all of the plants are adding a 3rd star and the text is changing to GREAT for all of them. what can I change to have the foreach loop check all plants and ONLY change the if statement criteria on each one if it meets it.

        StrainAtributes[] plants = (StrainAtributes[]) GameObject.FindObjectsOfType (typeof(StrainAtributes));
        foreach (StrainAtributes plant in plants) {

            if (plant.qualityScore <= 19)
            {
                star1.sprite = starGold;
            }
            if (plant.qualityScore >= 20 && plant.qualityScore <= 29)
            {
                star2.sprite = starGold;

                effect.AnimationManager.PlayAnimation();
            }
            else if (plant.qualityScore >= 30)
            {
                star3.sprite = starGold;
                effect.text = "GREAT!";
                effect.AnimationManager.PlayAnimation();
            }
            else {

            }

I think you’re not associating star1, star2, and star3 to individual plants. It looks like these are global.
In side the if i would expect something like plant.getComponent().sprite = starGold;

1 Like

sorry, so plantbar update is attached to each individual plant gameobject. Another script calls a foreach plant run plantbar update script. Each plant references its own attached stars on its own gameobject. this is why Id o not understand how its applying a 3rd star to each plant when plantbarupdate script in attached to each indivuidual plant and the function to change the stars is called on each plant.

so the script you posted is attached to each plant? i would think no, it’s the foreach loop
and because it’s not that’s why star1, star2, star3 are a global value, not for each plant

if (plant.qualityScore <= 19)
            {
                //star1.sprite = starGold; // does star for all plants
                plant.getComponent<plantScript>().enableStar;  //something like this.  you need to access each plant to enable the star just the one
            }
1 Like

ahh i figured it out. I do not know why i had a foreach loop on the plantbarupdate script. I removed it. Thanks guys.