How can i change the material of my player from all scenes with a button?

Im newer to unity. Im making a cube game where my cube has the tag “Player” set to it. I have a skin selector in my game that i want to allow the player to change the skin of the cube (just by changing the material) with a button. for some reason my button doesnt do anything to the player’s material. This is my code.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MaterialChanger : MonoBehaviour
{

public GameObject Player;
public Material skinMaterial;

private void OnMouseDown()
{
    Player.GetComponent<MeshRenderer>().material = skinMaterial;
}

}

That code should work, check if

  • Are you sure OnMouseDown() is been called? Add Debug.Log(“Mouse Down”); and check the console when the game is running to make sure its is been called.
  • Are player and skin material assigned in the editor?
  • Is it a MeshRenderer and not a SkinMeshedRenderer

You can try

Material[] materials = Player.GetComponent<MeshRenderer>().materials;
materials[0] = skinMaterial;
Player.GetComponent<MeshRenderer>().materials = materials;

But your code does work as I’ve tried it