N1ckGreek N1ckGreek -4 years ago 206
C# Question

Change Material of one game object only using Ray cast and Mouse click

I created the following code to see which game object i click but i cant find how to change the material of the object i click only, it changes the material of all objects which have the script.


public int TileGroup = 0; //Indicates the Tile Group Number.


public Rigidbody myRigidbody;
public Renderer myRenderer;
public Material tileDefaultMaterial;
public Material tileSelectedMaterial;
public Material tileSameGroupMaterial;

void Start () {
myRigidbody = GetComponent<Rigidbody> ();
myRenderer = GetComponent<Renderer> ();
tileDefaultMaterial = Resources.Load ("TileDefault", typeof(Material)) as Material;
tileSelectedMaterial = Resources.Load ("TileSelected", typeof(Material)) as Material;
tileSameGroupMaterial = Resources.Load ("TileSameGroup", typeof(Material)) as Material;

void Update () {
if (Input.GetMouseButtonDown (0)) {
TileClick ();

void TileClick (){

RaycastHit hitInfo = new RaycastHit ();
bool hit = Physics.Raycast (Camera.main.ScreenPointToRay (Input.mousePosition), out hitInfo);

if (hit) {
Debug.Log ("Hit: " + hitInfo.transform.gameObject.name);

if (hitInfo.transform.gameObject.tag == "Tile") {
Debug.Log ("Hit a Tile!");
myRenderer.material = tileSelectedMaterial;
} else {
Debug.Log ("Hit Empty Space!");

Answer Source

As you are running

void Update()

Whenever you click (no matter where), Input.GetMouseButton(0) will be true in all instances of scripts. So you end up changing color of all the objects. Instead you can try the OnMouseDown() method.

void OnMouseDown() 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download