Unity3d---object plus click event

Table of contents

1. Add a collider to the object that needs to be clicked

2. Hierarchical panel plus EventSystem

3. Camera plus Physics Raycaster

4. The object responds to the click event alone

5. Control the script to realize the click event of each object

6. Block the object click event when clicking on the ui



1. Add a collider to the object that needs to be clicked

 

2. Hierarchical panel plus EventSystem

 

3. Camera plus Physics Raycaster

2d 3d add on demand

 

4. The object responds to the click event alone

Create a separate script to hang on the object that responds to clicks

public class ClickObj : MonoBehaviour, IPointerClickHandler
{
    public void OnPointerClick(PointerEventData event)
    {
        Debug.LogError("我被点了");
    }
}

5. Control the script to realize the click event of each object

private void Update()
    {
        if (subCamera[0].activeSelf)
        {
            if (Input.GetMouseButtonDown(0))
            {
                ray = Camera.main.ScreenPointToRay(Input.mousePosition);
                if (Physics.Raycast(ray, out hit))
                {
                    obj = hit.collider.gameObject;
                    //根据物体名 进行下一步操作
                    switch (obj.name)
                    {
                        case "add_dp": 
                            Debug.LogError("aaa");
                            break;
                        case "add_ck":
                            break;
                        case "add_jxb":
                            break;
                        case "add_lt":
                            break;
                        case "add_cm":
                            break;
                        case "add_kqf":
                            break;
                    }
                }
            }
        }
        else if (subCamera[1].activeSelf)
        {
            if (Input.GetMouseButtonDown(0))
            {
                ray = Camera.main.ScreenPointToRay(Input.mousePosition);
                if (Physics.Raycast(ray, out hit))
                {
                    obj = hit.collider.gameObject;
                    //根据物体tag 进行下一步操作
                    switch (obj.tag)
                    {
                        case "aaa":
                            Debug.LogError("aaa");
                            break;
                        case "bbb":
                            Debug.LogError("bbb");
                            break;
                    }
                }
            }
        }
    }

6. Block the object click event when clicking on the ui

if (Input.touchCount == 1)
        {
            if (EventSystem.current.IsPointerOverGameObject(Input.GetTouch(0).fingerId)) { return; }
        }
        else
        {
            if (EventSystem.current.IsPointerOverGameObject()) { return; }
        }

Guess you like

Origin blog.csdn.net/lalate/article/details/130342110