- Home /
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;
}
}
Answer by MickyX · May 08 at 09:27 AM
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
when i click the button with debug log nothing pops up in the console. should i have something on the "On Click" in the inspector? Very confusing to me because i have other buttons that work in my game but cant get these to work.
Without seeing your full set up its hard to give direct advice. However I would guess that yes you should have something in the On Click in the inspector if it is a UI button.
You need to add an event to the button, and drag the gameobject that holds the script onto that event. In the drop down you can select your script and select "OnMouseDown" that will call the function when you click the button