- Home /
clicking on a mesh in game
hi I'm fairly new to unity but I was wondering if I have a first person game can you have an event happen when a mesh is clicked on by the player. If this is possible how would I go about doing it?
thanks beforehand all answers appreciated
Answer by testure · Jun 01, 2011 at 10:13 PM
Iggy's answer isn't exactly right, because it doesn't tell you when you've clicked on a mesh- it just tells you that the player has clicked... anywhere.
you still need to test for the mouse button, but you need to raycast from the camera where the mouse clicked, and find out what object it hit.
something like this should work (untested, javascript):
if(Input.GetMouseButtonDown(0))
{
var ray : Ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if(Physics.Raycast(ray, hit))
Debug.Log("Mouse Down Hit the following object: " + hit.collider.name);
}
thanks i havent tried either but this seems perfect! thanks guys!
I'd like to chip in on this, since I just needed it and found a slight issue with it. I had to declare the hit variable.
if (Input.Get$$anonymous$$ouseButtonDown(0)){
var ray : Ray = Camera.main.ScreenPointToRay(Input.mousePosition);
var hit : RaycastHit;
if (Physics.Raycast(ray,hit)){
Debug.Log("$$anonymous$$ouse Down hit: "+hit.collider.name);
}
}