Unity模拟点击事件接口

在VR开发中,我们常常遇到这样一种需求:将某个已经有的某个VR游戏移植到其他虚拟现实设备中。要重新接各种各样sdk.有的sdk没有提供手柄点击按钮的接口,有的时候甚至没有手柄,要改成视点点击。这个时候需要用到Unity中按钮点击的功能
要注意的点有很多。

  • VR中很多UI都是wordspace,很多操作要基于射线进行
  • 基于射线检测的UGUI按钮必须要绑定上BoxCollider(注意必须要绑定3d的而不是2d的)

MyButton.cs:

using UnityEngine;
using UnityEngine.UI;

public class MyButton : MonoBehaviour
{
    public Button button;
    // Start is called before the first frame update
    void Start()
    {
        button.onClick.AddListener(OnButtonClick);
    }

    private void OnButtonClick()
    {
        Debug.Log("按钮点击执行事件");
    }

}

RayClicker是用来发射射线的物体:

public class RayClicker : MonoBehaviour
{
	 public GameObject currentObj;
     PointerEventData data;
     void start(){
     	data = new PointerEventData(EventSystem.current);
     }
     public void OnClick(){
     	Ray ray = new Ray(transform.position, transform.forward * 1000);
        Debug.DrawLine(transform.position, transform.position + transform.forward * 1000, Color.red);

        RaycastHit hit;
        Physics.Raycast(ray, out hit)
        if (hit.collider!=null)
        {
        		currentObj = hit.collider.gameObject;
             if(currentObj!=null){
             	ExecuteEvents.Execute<IPointerClickHandler>(currentObj,data,ExecuteEvents.pointerClickHandler);
             }
        }
     }
}

之所以用这样的写法而不直接调用按钮上的OnButtonClick事件是为了在按钮增加的时候不用修改代码适配新的按钮。而且调用ExecuteEvents还可以在原有逻辑不修改的情况无缝移植程序。

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值