这里用IPointerClickHandler举例(api中这样解释):
也就是在我们的被点击的类中实现了接口后,在实现方法OnPointerClick,在这个方法里操作点击后的处理。
到这里,需要我们开发的只有一个脚本,Demo里的EventClick.cs
using UnityEngine;
using UnityEngine.EventSystems;
public class EventClick : MonoBehaviour,IPointerClickHandler
{
public void OnPointerClick(PointerEventData eventData)
{
print("点击了::"+this.name);
}
}
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
public class ClickEventTrigger : MonoBehaviour
{
public void OnClick()
{
print("MyOnClick 点击了::"+this.name);
}
}
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");
}
}
文章来源:https://www.toymoban.com/news/detail-480700.html
文章来源地址https://www.toymoban.com/news/detail-480700.html
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);
}
}
}
}
}
到了这里,关于Unity3D-场景中3D物体添加点击事件的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!