# How to set the color of a game object as of the other?

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;
}


}

• Can I assume that player does already reference the player? May 18 '20 at 12:40
• 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 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.

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