Troubles with changing an attribute of every gameobject

I’ve written a corountine to use a sprite mask to show nearby sprites and so far, that works flawlessly. However, when it comes to changing the opacity of every gameobject in the scene, I’m starting to find troubles. There isn’t very many gameobjects in the current scene so I’m not too worried about the optimization. I created an array to store all the gameobjects here:

public GameObject[] objects;

and then I try to grab all the objects in the scene with this:

// Start is called before the first frame update
void Start()
{
    playerTransform = transform;
    objects = GameObject.FindGameObjectsWithTag("Untagged");
}

and this is the method I’m using:

IEnumerator sonar()
{
    sonarMask.transform.DOScale(new Vector3(20f, 20f, 0f), 0.7f);
    yield return new WaitForSeconds(1f);
    Debug.Log("Started loop");
    foreach (var obj in objects)
    {
        Debug.Log("Found obj");
        SpriteRenderer spriteRenderer = obj.GetComponent<SpriteRenderer>();
        if (spriteRenderer != null)
        {
            Debug.Log("started fade");
            spriteRenderer.DOFade(0f, 5f);
        }
    }
    yield return null;
}

The script never displays “Found obj” or “started fade” leading me to believe that there are no gameobjects in the array. Can I get some help?

You are correct if you’re not worried about performance, since using GetComponent like that is really really bad for performance, lol.

However, you are declaring an array, but it has “no slots” within it, as array’s need to have a index quantity. If you are unsure how many to index, you are better off using List’s, as List’s do not require a set index quantity.

You will, hopefully, in time realize that aiming for performance is always needed, since doing things performantly actually refer to doing things the right way(kinda). So when you decide to scale up, or make your game more expansive, everything is already working tip-top, and no further “refactoring” will be needed(which wastes days of time and frustration).

So the best example I can give, that solves all of your problems noted, is to create a list of the instances(scripts), this way you can change whatever’s needed easily. But you might argue that each object you reference has different scripts, simple! Just create a parent class, that all the child objects derive from. Therefor the instance list only needs to be the parent, example:

public class Inventory : MonoBehaviour
{
    // stuff
}
  
public class Potions : Inventory
{
    // stuff
}
  
public class Weapons : Inventory
{
      // stuff
}

And then all your player class would need is :

public List<Inventory> objects = new List<Inventory>();
public GameObject myWeapon;
  
for (int i = 0; i < objects.Count; i++)
{
    if (objects.damage >= 25) // example
        myWeapon = objects.gameObject;
}

Which is a pretty bad example, but hopefully you get the idea :slight_smile: