- Home /
How to check if click mouse on object
Hi! I want to check if player click mouse on object, movie will play. I put Input.GetMouseButton (0) function on the object but if click position is not in object,this script will run too
Please tell me how to to this and I want to know how to check mouse position in "Object area", I know about use Raycast to get mouse position but I don't know how to check if my mouse position is in my object area, how to do this? Thanks!
Answer by Sundar · Jan 13, 2014 at 06:27 PM
Make sure your object has a collider then try this
function Update () {
if (Input.GetMouseButtonDown(0)) {
var hit: RaycastHit;
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, hit)) {
if (hit.transform.name == "MyObjectName" )Debug.Log( "My object is clicked by mouse");
}
}
Thanks for posting this! How would this work in c#? also, how would you do this if you wanted to check if the object that was hit had a certain tag on it?
@Stephanie_Brooks ins$$anonymous$$d of using hit.collider.name, replace the .name with .tag.
C# translation
void Update () {
if (Input.Get$$anonymous$$ouseButtonDown(0)) {
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit)) {
if (hit.transform.name == "$$anonymous$$yObjectName" )
{print( "$$anonymous$$y object is clicked by mouse");}
}
}
Answer by nbg_yalta · Jan 13, 2014 at 06:26 PM
You can use OnMouseDown or raycast check. here is onmousedown example:
void OnMouseDown()
{
//Do something
}
Be sure you have collider on your object.
Oh I for got that we have On$$anonymous$$ouseDown function thank you