Change GameObject color by C# script

Hi. I have a sample scene like in the picture. What I want is to change the 2nd cube (the one inside GameObject2).
I used:

GameObject.Find("Cube").GetComponent<Renderer>().material.color = new Color(0, 204, 102);

But it only change color of the 1st cube.
So is anyway to access to the 2nd cube by code?
Thank you

1 Like
     foreach(GameObject gameObj in GameObject.FindObjectsOfType<GameObject>())
     {
         if(gameObj.name == "Cube")
         {
             gameObj.GetComponent<Renderer>().material.color = new Color(0, 204, 102);
         }
     }

Hi raarc,
Thank you for replying to me.
May I ask a further question? If in C# script, I create a public GameObject named Test:

public GameObject Test;

Then drag/attach the GameObject1 to Test in Unity.
So in C# script, is there any way for me continue to access, from Test to GameObject2 to Cube, then change its color?
Thank you

Test.transform.GetChild(0).transform.Find("Cube").GetComponent<Renderer>().material.color = new Color(0, 204, 102);
1 Like

its as simple as adding a second line for the other cube.
just use the name of the other cube insead.

For example:
(I’m using this for my game to render colors for all the obstacles)

GameObject.Find("obstacle1").GetComponent<Renderer>().material.color = new Color(0, 0, 0);
GameObject.Find("obstacle2").GetComponent<Renderer>().material.color = new Color(0, 0, 0);
var cubeRenderer = GameObject.Find("Cube").GetComponent<Renderer>();
cubeRenderer.material.SetColor("_Color", new Color(0, 204, 102));
1 Like