unity-game-engineraycastingonmouseclick

Handle mouse click on a gameobject - Unity3d


I have a small city mesh and an apartment 3d model. I add the mesh to my scene and place the 3d model on the mesh.

I try to handle mouse click only on 3d model. I use below code. But I click anywhere on the screen, it sets as sound = true

I add a mesh collider to 3d model gameobject.

if (Input.GetMouseButtonDown (0)) {
            Plane p = new Plane (Camera.main.transform.forward , transform.position);
            Ray r = Camera.main.ScreenPointToRay (Input.mousePosition);
            float d;
            if(p.Raycast (r, out d)) {
                sound = true;
}   

How can I solve it?


Solution

  • you can check tag/name of game object. you need to use like that:

    void Update() 
    {
        if (Input.GetMouseButtonDown (0)) {
    
            Plane p = new Plane (Camera.main.transform.forward , transform.position);
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;
    
            if (Physics.Raycast(ray, out hit, 100)) 
            {
                //Choose one of them below!!!
    
                /// Name Comparison
                if(hit.collider.gameObject.name.equals("NameOfTheObject")){
                   ///Do Logic
                }
    
                //Tag Comparison
                if(hit.collider.gameObject.CompareTag("TagOfTheObject")){
                    ///Do Logic
                }
            }
        }
    }