用鼠标点击游戏对象 - Unity3d

时间:2016-03-25 09:17:48

标签: unity3d raycasting onmouseclick

我有一个小城市网和一个公寓三维模型。我将网格物体添加到场景中并将3d模型放在网格上。

我尝试仅在3d模型上处理鼠标点击。我使用下面的代码。但我点击屏幕上的任意位置,它设置为sound = true

我在3d模型游戏对象中添加了一个网格对撞机。

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;
}   

我该如何解决?

1 个答案:

答案 0 :(得分:0)

你可以检查游戏对象的标签/名称。你需要这样使用:

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
            }
        }
    }
}
相关问题