I am 15 year old Indian student and I am creating my first 2D game in Unity. I have set the color of my player as Random and I have to set the color of my game object as of my player. But the color of the player changes Randomly. So I can't set a specific color to my game object. What I have tried:

public class SetColor : MonoBehaviour {

public GameObject player;  
public SpriteRenderer sr;  
void Start() {  
     sr = GetComponent<SpriteRenderer>();  
     sr.color = Color.player;  


But this not worked. Please reply how to code it correctly?

  • \$\begingroup\$ Can I assume that player does already reference the player? \$\endgroup\$ – Philipp May 18 '20 at 12:40
  • \$\begingroup\$ when the player respawn the color of the player is changed and I want the object to change color when the color of the player is changed \$\endgroup\$ – Mokshith May 18 '20 at 12:43

The class Color has a couple predefined colors, but no color named "player". And the player itself doesn't have a color either. The player has a SpriteRenderer which has a color.

So what you need to do is obtain the SpriteRenderer component of the player and then the color from that SpriteRenderer.

 mySpriteRenderer = GetComponent<SpriteRenderer>();  
 playerSpriteRenderer = player.GetComponent<SpriteRenderer>();  
 mySpriteRenderer.color = playerSpriteRenderer.color;  

Further, if you want the sprite to change color when the player changes color, then you shouldn't put the code into Start, you should put it into Update. This will update the color every frame. A more elegant and performance-friendly solution would only update the color when it actually changed, but that would make the above code a lot more complicated. So I would recommend to do it this way for now to get started.

  • \$\begingroup\$ Thanks a lot for your response \$\endgroup\$ – Mokshith May 18 '20 at 12:56
  • \$\begingroup\$ It worked as I wanted. I have spent 2 hours trying to solve this problem and atlast you saved my day. \$\endgroup\$ – Mokshith May 18 '20 at 13:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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