Select sphere to change color after button click

Hi there

I have a audio player object where I want to change the color of all spheres in the scene, by pressing the play button but can’t find a way to select them without having errors.

Here’s my function:

public void ChangeColor()
    {
        var sphere = GameObject.Find("Sphere");
        sphere.GetComponent<Material>().color = Color.green;
    }

But I’m seeing error “MissingComponentException: There is no ‘Material’ attached to the “Sphere” game object, but a script is trying to access it.” when the sphere has a Material attached.

Another post due to the horrible API known as GameObject.Find()… you should stay away from this.

For one, you have “all spheres”.

Line 3 above might find a GameObject called “Sphere”. Which one? Who knows! All of them? Nope! Just one… maybe. And it won’t find it if it is actually called “Sphere (Clone)” for instance.

Make a public field in your script for which Sphere you want to change, drag it in in the inspector, and don’t use GameObject.Find().

Remember: GameObject.Find() is the root of all evil. It’s probably at least partially to blame for coronavirus in fact (just kidding… it’s not).