I want to get the object color, when I start the game. How do I do this?

enter image description here

public Renderer cube;
public float r,b,g,a;

void Start() {
            r = cube.GetComponent<Renderer>().material.color =
            b = cube.GetComponent<Renderer>().material.color =
            g = cube.GetComponent<Renderer>().material.color =
            a = cube.GetComponent<Renderer>().material.color =

}
  • Did you try grabbing color.r, color.g, etc? – Gnemlock Dec 25 '16 at 6:29
  • We solve this, check please "Shuvro Sarkar" answer. Thank you. – user43474 Jan 7 '17 at 17:55
up vote 7 down vote accepted

Its actually simple. Just use Color32 class to get the r, b, g, a of your desired gameobject. Here is an Example Code. Here I used a cube gameobject and got the color of its material.

public class FirstScript : MonoBehaviour 
{
// Use this for initialization
  void Start () 
  {
    Color32 objColor;
    objColor = gameObject.GetComponent<MeshRenderer>().material.color;

    print(objColor.r + " "+ objColor.g + " "+ objColor.b+ " "+ objColor.a + " ");
  }
}

Result

  • 1
    This answer is correct for the most simple case, but sometimes you have an object with multiple materials. Then you need to pick the right one from the renderer.materials array. Also, your material might use a more complex shader which has more than one color. Then you need to use the material.GetColor method to get the color you want. – Philipp Dec 25 '16 at 10:37
  • In Order to get the color on the screen one could also use render texture with pixel get access and use worldtoscreenpoint to get the pixel positions of the object. Then the exact pixel color can be extracted. However this will also introduce shadows etc.. But in some more sophisticated cases (where simple material access would yield wrong results) this could work. – M156 Jan 18 '17 at 7:15

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.