Unity3D-add click event to 3D objects in the scene

Unity3D - add mouse click event to 3D objects in the scene
The mouse clicks on the 3D object to trigger. Unity essentially has two types: one is triggered by an event (event), and the other is triggered by a ray (ray) to judge the passing object. The principles of these two triggers are different, no matter which trigger must meet the trigger requirements, since the principles are different, the trigger requirements are also different, the following three different methods are described in detail.
Unity version 5.6.2f Unity API version 2019.1 
Reference Unity API: Redirect to... title of new-page
1. Implement the interface IPointerClickHandler through events 
First understand the interface IPointerClickHandler, the connection tree relationship is  UnityEngine.EventSystems.Interfaces.IPointerClickHandler , let's see what other interfaces it can implement


Here is an example with IPointerClickHandler (this is explained in the api):


That is, after implementing the interface in our clicked class, implement the method OnPointerClick, and operate the post-click processing in this method.
Since it is an event, first meet the requirements of event triggering:
1. Add the PhysicsRaycaster script to the Camera in the scene.


 
2. Add the event system EventSystem in the scene, as shown in the figure:


 
After clicking Add Default..., the following figure appears:


 
3. Here comes the important point, set the clicked object (3D) object, be sure to bring a trigger (Collider), and then hang the script of post-click processing on the clicked object.



So far, we need only one script to develop, EventClick.cs in Demo 
 
using UnityEngine;
using UnityEngine.EventSystems;

public class EventClick : MonoBehaviour,IPointerClickHandler
{
    public void OnPointerClick(PointerEventData eventData)
    {
        print("点击了::"+this.name);
    }
}

Run click cube:


 
2. Through the event, attach the script EventTrigger
This is also achieved through the same event, and the requirements for event triggering must also be met according to one mile (I don’t understand! Look up):
1. Add the PhysicsRaycaster script to the Camera in the scene.
2. Add the event system EventSystem in the scene;
After completing the above two steps, 3 is different from Yili.
3. There are two methods here, namely 3.1 and 3.2, but the usage is different, and the principle is the same.
First add an EventTrigger script to the clicked object.


 
3.1, is a static add event trigger
Add event type to EventTrigger, select as needed,


 
Select click event PointerClick in Demo


 
Add trigger execution function to PointerClick


 
The execution function here is the ClickEventTrigger.cs class we developed below, just add this script to the clicked object.
 
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;

public class ClickEventTrigger : MonoBehaviour 
{
public void OnClick()
    {
        print("MyOnClick 点击了::"+this.name);
    }
}
At this point, the static addition of events is complete, and the running effect is as follows:


 
3.2, is to dynamically add event triggers
Dynamic triggering is much more convenient to operate in the Unity editor, just add EventTrigger to the clicked object, and then add our script ClickEventTrigger.cs to the clicked object, and the rest are in the code Finish.
 
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;

public class ClickEventTrigger : MonoBehaviour {

// Use this for initialization
void Start () {

        //获取或添加EventTrigger组件
        EventTrigger trigger = transform.GetComponent();
        if (trigger == null)
        {
            trigger = transform.gameObject.AddComponent();
        }
        //初始化EventTrigger.Entry的数组 如果这里初始化了事件触发数组,那么在ide静态添加的事件会丢失
        //trigger.triggers = new List();
        //创建各种 EventTrigger.Entry的类型
        EventTrigger.Entry entry = new EventTrigger.Entry();
        entry.eventID = EventTriggerType.PointerEnter;//设置Entry的eventID类型 即EventTriggerType的各种枚举(比如鼠标点击,滑动,拖动等)
        UnityAction callback = new UnityAction(OnPointerEnter);  //注册代理
        entry.callback.AddListener(callback);//添加代理事件到EventTrigger.Entry

        EventTrigger.Entry entry2 = new EventTrigger.Entry();
        entry2.eventID = EventTriggerType.PointerDown;
        UnityAction callback1 = new UnityAction(OnPointerDown);
        entry2.callback.AddListener(callback1);

        //在EventTrigger.Entry的数组添加EventTrigger.Entry
        trigger.triggers.Add(entry);
        trigger.triggers.Add(entry2);
    }

    private void OnPointerDown(BaseEventData arg0)
    {
        Debug.Log("OnPointerDown");
    }

    private void OnPointerEnter(BaseEventData arg0)
    {
        Debug.Log("OnPointerEnter");
    }
}

operation result:


 
3. Through rays, RayCastHitControl
This method is mainly through ray emission, judging the object that the ray passes through, and judging whether the object is clicked according to a specific mark (for example: the tag of the object, and the name of the object)
Only 3D objects are needed here with a clear unique identifier, plus the ClickRayCastHitControl.cs we developed.


 
1. Create an object (Cube) in the scene, then click Tag - AddTag...- in the Tags list under the Inspector panel, click +, and enter the name of the Tag you want to add. After creating the Tag, go back to the scene and select the Tag you just created for this Cube.


 
2. Create a Cube and name it in the demo (BeiJiChaun). This name is the identification of the ray passing through judgment, and the object is created.


 
3. Create a separate layer and mount the script we developed.


 
operation result:


 
Full code:
 
using UnityEngine;

public class ClickRayCastHitControl : MonoBehaviour {

    Ray ray;
    RaycastHit hit;
    GameObject obj;
    // Use this for initialization
    void Start () {

}

    // Update is called once per frame
    
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            Debug.Log("点击鼠标左键");
            ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            if (Physics.Raycast(ray, out hit))
            {
                Debug.Log(hit.collider.gameObject.name);
                obj = hit.collider.gameObject;
                //通过名字
                if (obj.name.Equals("BeiJiChuan"))
                {
                    Debug.Log("点中" + obj.name);
                }
                //通过标签
                if (obj.tag == "ClicObj")
                {
                    Debug.Log("点中" + obj.name);
                }
            }
        }
    }
}

Guess you like

Origin blog.csdn.net/u013774978/article/details/129847810