Unity clicks on 3D objects

Table of contents

1.OnMouse

2. Ray detection (first the object must have a Collider and then mount the script)

3. Game object EventTrigger object dynamic event monitoring

3.1 Static addition of event triggering

 3.2 Dynamically add event triggers

 4. Implement the interface IPointerClickHandler through events


1.OnMouse

  1. Add a script component to your 3D object. This script will handle click events and return object information. For example, you could name this script ObjectInfo.
  2. InObjectInfoscript, add the following code:
using UnityEngine;

public class ObjectInfo : MonoBehaviour {

private void OnMouseDown()

{ // 当鼠标点击物体时触发

// 获取物体的信息

string objectName = gameObject.name;

Vector3 objectPosition = gameObject.transform.position;

// 输出物体信息到控制台 Debug.Log("物体名称:" + objectName); Debug.Log("物体位置:" + objectPosition); // 在这里你可以对物体信息进行自定义操作,比如将其显示在UI界面上或进行其他逻辑处理 } 
}
  1. Save the script and return to the Unity Editor. Add theObjectInfoscript to the 3D object you want to get information from. Make sure this object has a collider component (such as a Box Collider) so that it can detect mouse click events.

Now, when you run the game and click on the selected 3D object, the object's name and location information will be displayed in the Unity console. You can send this information to the UI interface, store it in variables, or perform other custom processing as needed.

2. Ray detection (first the object must have a Collider and then mount the script)

using UnityEngine;
using System.Collections;
 
public class RayCastHitControl : MonoBehaviour {
 
	// Use this for initialization
	void Start () {
	
	}
    Ray ray;
    RaycastHit hit;
    GameObject obj;
    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("BeiJiuChuan"))
                {
                    Debug.Log("点中"+obj.name);
                }
                //通过标签
                if (obj.tag == "move")
                {
                    Debug.Log("点中" + obj.name);
                }
            }
        }
    }

3. Game object EventTrigger object dynamic event monitoring

Instructions

3.1 Static addition of event triggering

Add an event type to EventTrigger and select it as needed.

Select the click event PointerClick in the Demo 

 The execution function here is the class ClickEventTrigger.cs we developed below. Just add this script to the clicked object.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ClickEventTrigger : MonoBehaviour
{
    public void OnClick()
    {
        print("MyOnClick 点击了::" + this.name);
    }
}

At this point, the static addition of events is completed, and the running effect is:

 

 3.2 Dynamically add event triggers

 Dynamic triggering is much more convenient in the Unity editor. You only need to add EventTrigger to the clicked object, and then add our script ClickEventTrigger.cs to the clicked object. The rest is in the code. Finish.

using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;

public class ClickEventTrigger2 : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        //获取或添加EventTrigger组件

        EventTrigger trigger = transform.GetComponent<EventTrigger>();

        if (trigger == null)

        {

            trigger = transform.gameObject.AddComponent<EventTrigger>();

        }

        //初始化EventTrigger.Entry的数组

        trigger.triggers = new List<EventTrigger.Entry>();

        //创建各种 EventTrigger.Entry 的类型

        EventTrigger.Entry entry = new EventTrigger.Entry();

        //设置Entry的eventID类型 即EventTriggerType的各种枚举(比如鼠标点击,滑动,拖动等)

        entry.eventID = EventTriggerType.PointerEnter;

        //注册代理

        UnityAction<BaseEventData> callback = new UnityAction<BaseEventData>(OnEventTrigger);

        //添加代理事件到EventTrigger.Entry

        entry.callback.AddListener(callback);



        EventTrigger.Entry entry2 = new EventTrigger.Entry();

        entry2.eventID = EventTriggerType.PointerDown;

        UnityAction<BaseEventData> callback1 = new UnityAction<BaseEventData>(OnMouseDown);

        entry2.callback.AddListener(callback1);



        //在EventTrigger.Entry的数组添加EventTrigger.Entry

        trigger.triggers.Add(entry);

        trigger.triggers.Add(entry2);



    }
    private void OnMouseDown(BaseEventData arg0)
    {

        Debug.Log("OnMouseDown");

    }



    private void OnEventTrigger(BaseEventData arg0)
    {

        Debug.Log("OnEventTrigger");

    }

}

 operation result:

 4. Implement the interface IPointerClickHandler through events

Since it is an event, first meet the requirements for event triggering:

  1. Add the PhysicsRaycaster script to the Camera in the scene

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

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

    At this point, we only need to develop one script, EventClick.cs in the Demo. 

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

    Run click cube:

    Unity3D-Add click events to 3D objects in the scene

Guess you like

Origin blog.csdn.net/2302_76830411/article/details/131449395