Color changing an object based on the color of the player.

Hello!

I’m trying to have a cube’s color change based on the color of the player, and stay that color. Having the cube stay that color is where I’m having an issue. I have the first script (Colors), attached to the Player, and it is a simple color change based on a number push. The second script (ColorChange) is on the cube, and I have the Player attached to the gameObject on the script. I’m able to get the cube’s color to change based on the initial collision based on the player’s color. However, if I change the color of the player, the cube will also change that color, even if there is no second collision.

Ultimately, I’m trying to figure out is this: If Player is red, then have cube turn red on collision, and have cube stay red when I change the color of the player to blue. Then upon second collision when the player is blue, have the cube blue, etc… Any help would be grealy appreciated, Thanks!


public class Colors : MonoBehaviour
{
Material mat;
public Color white = new Color(1f,1f,1f,1f);
public Color red = new Color(1f,0f,0f,1f);
public Color yellow = new Color(1f,1f,0f,1f);
public Color blue = new Color(0f,0f,1f,1f);
public Color black = new Color(0f,0f,0f,1f);

void Start () 

{
	mat = GetComponent<Renderer>().material;
}

void Update () 
{
	if (Input.GetKeyDown (KeyCode.Alpha1)) 
	{
		mat.color = white;
	}
	if (Input.GetKeyDown (KeyCode.Alpha2)) 
	{
		mat.color = red;
	}
	if (Input.GetKeyDown (KeyCode.Alpha3)) 
	{
		mat.color = yellow;
	}
	if (Input.GetKeyDown (KeyCode.Alpha4)) 
	{
		mat.color = blue;
	}
	if (Input.GetKeyDown (KeyCode.Alpha5)) 
	{
		mat.color = black;
	}

}

}

public class ColorChange : MonoBehaviour {

Material mat1;
public Color white = new Color(1f,1f,1f,1f);
public Color red = new Color(1f,0f,0f,1f);
public Color orange = new Color(1f,.5f,0f,1f);
public Color yellow = new Color(1f,1f,0f,1f);
public Color green = new Color(0f,.5f,0f,1f);
public Color blue = new Color(0f,0f,1f,1f);
public Color purple = new Color(.5f,0f,1f,1f);
public Color black = new Color(0f,0f,0f,1f);
public GameObject Player;

bool colourChangeCollision = false;

void Start () 

{
	mat1 = Player.GetComponent<Renderer>().material;
}

void OnCollisionEnter(Collision other)
{
	colourChangeCollision = true;
}

void checkColourChange()
{        
	if (colourChangeCollision) 
	{
		transform.GetComponent<Renderer> ().material.color = mat1.color;
	}
}

void Update()
{
	checkColourChange();
}

}

Hello ,

Change your method checkColourChange with this :-

void checkColourChange()
{
if (colourChangeCollision)
{
transform.GetComponent ().material.color = mat1.color;
}
}

Also you dont need to make variable of colors As Unity has its own class for color .

so you can change color by writing mat.color = Color.red;