Raycasting Button (Game object) with single message

Hi,

I am new to unity. I want to use RayCast for multiple buttons. All buttons will have same tag “ButInfo”. Each button will do same job and only difference will be its id. Depending upon its id i want to display message. There will be around 50 buttons on the screen. But when a button is clicked, it displays messages of all 50 buttons.

You clicked a button Button1
You clicked a button Button2
You clicked a button Button3
You clicked a button Button4
and so on

But i want only one message when a button is clicked with its ID.

Here is the code that are attached to all buttons.

using UnityEngine;
using System.Collections;
    
public class test : MonoBehaviour {
RaycastHit hit;
public int myID; //0,1,2, ...  id as array index

string[] msg = new string []{"Button1","Button2","Button3","Button4","Button5","Button6"};
	
void Update () {
	Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
	if (Physics.Raycast(ray, out hit)){

       if (hit.collider.transform.tag == "ButInfo"){
		if(Input.GetMouseButtonDown(0)){	
			Debug.Log ("You clicked a button "+msg[myID]);	
		}
      }
	}		
}

}

Please Help.

Hi,

When you are calling physics.raycast, it will hit a collider, say, collider with ID 12, as expected. But what happens is: the update() of each of your 50 “test” objects will be called, and each of the 50 will have the exact same result: ray will hit collider ID 12. Then each of them will display a message about them being hit, with their own ID (not ID 12).

You should have only one gameObject (a kind of manager object) with such raycasting code in the Update() callback, then this object should use collider.gameObject to know what object has been hit (using GetComponent to get the “test” component and access test.myID)