Search Unity

  1. If you have experience with import & exporting custom (.unitypackage) packages, please help complete a survey (open until May 15, 2024).
    Dismiss Notice
  2. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice

Change GameObject color by C# script

Discussion in 'Scripting' started by misterloser, Jul 1, 2020.

  1. misterloser

    misterloser

    Joined:
    May 2, 2020
    Posts:
    8
    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:
    Code (CSharp):
    1. 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
     

    Attached Files:

    zxartisxz likes this.
  2. raarc

    raarc

    Joined:
    Jun 15, 2020
    Posts:
    535
    Code (CSharp):
    1.  
    2.  
    3.      foreach(GameObject gameObj in GameObject.FindObjectsOfType<GameObject>())
    4.      {
    5.          if(gameObj.name == "Cube")
    6.          {
    7.              gameObj.GetComponent<Renderer>().material.color = new Color(0, 204, 102);
    8.          }
    9.      }
    10.  
    11.  
     
  3. misterloser

    misterloser

    Joined:
    May 2, 2020
    Posts:
    8
    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:
    Code (CSharp):
    1. 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
     
  4. raarc

    raarc

    Joined:
    Jun 15, 2020
    Posts:
    535
    Code (CSharp):
    1. Test.transform.GetChild(0).transform.Find("Cube").GetComponent<Renderer>().material.color = new Color(0, 204, 102);
     
    jcameron47 likes this.
  5. Timothysorber

    Timothysorber

    Joined:
    Oct 4, 2021
    Posts:
    6
    its as simple as adding a second line for the other cube.
    just use the name of the other cube insead.
     
  6. Timothysorber

    Timothysorber

    Joined:
    Oct 4, 2021
    Posts:
    6
    For example:
    (I'm using this for my game to render colors for all the obstacles)
    Code (CSharp):
    1. GameObject.Find("obstacle1").GetComponent<Renderer>().material.color = new Color(0, 0, 0);
    2. GameObject.Find("obstacle2").GetComponent<Renderer>().material.color = new Color(0, 0, 0);
     
  7. abdeallahhallou33

    abdeallahhallou33

    Joined:
    Apr 1, 2023
    Posts:
    1
    Code (CSharp):
    1. var cubeRenderer = GameObject.Find("Cube").GetComponent<Renderer>();
    2. cubeRenderer.material.SetColor("_Color", new Color(0, 204, 102));
     
    Samwich2000 likes this.