Can't find material? (MissingComponentException)

I’m trying to make an effect where the color of the player and the color of the object they collide with swap during runtime.

Here’s my code with the comments:

public Color newColor;
public Color oldColor;
public GameObject Object;
//upon collision
void OnCollisionEnter (Collision collision) {
    //object collided with is stored
    Object = collision.collider.gameObject;
    //color of object is stored
    newColor = Object.GetComponent<Material>().color;
    //current color of subject is stored
    oldColor = gameObject.GetComponent<Material>().color;
    //subject becomes color of object
    GetComponent<Material>().color = newColor;
    //and vice versa
    Object.GetComponent<Material>().color = oldColor;
}

My goal is to have the colors of the materials of those objects change, as this would theoretically update the color of all objects with these Materials applied, right?

The problem is, when I try to run it, I get a MissingComponentException error, in which it tells me the objects do not have a material attached to them (they do) and as such Unity cannot swap the colors of the Materials if it can’t find them.

I’ve looked at people who have had this same error with other components but none of them seem similar to this issue. Any suggestions?

A Material is not a component and as such can not be attached to a gameobject. Therefore it can’t be aquired using GetComponent. A material is used by almost every Renderer component, Usually a MeshRenderer or SkinnedMeshRenderer. The MeshRenderer component does have a material and materials property where you can access the material(s) used by this renderer.

Materials are usually stored as assets in your project and dragged into the materials array of a renderer. Note that the Renderer also has a sharedMaterial and sharedMaterials property. When using that you access the actual Material asset which may be shared by several objects. Changing this material will affect all objects that use the same material (and don’t have their own instance). When you access material or materials Unity will automatically instantiate the shared material for this renderer. So changed to material will only affect this renderer.

I modified your code a bit. Try this:

	public Color newColor;
	public Color oldColor;
	public GameObject Object;
	
	void OnCollisionEnter (Collision collision) {
		
		Object = collision.collider.gameObject;
		
		newColor = Object.GetComponent<MeshRenderer>().material.color;
		
		oldColor = gameObject.GetComponent<MeshRenderer>().material.color;
		
		GetComponent<MeshRenderer>().material.color = newColor;
		
		Object.GetComponent<MeshRenderer>().material.color = oldColor;
	}