在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还可以在原有逻辑不修改的情况无缝移植程序。