预处理,判断当前平台
void LateUpdate()
{
#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
PC();
#endif
#if UNITY_EDITOR || UNITY_ANDROID
Mobile();
#endif
}
[注]
if的作用是程序流控制,会直接编译、执行。
#if是对编译器的指令,其作用是告诉编译器,有些语句行希望在条件满足时才编译。
射线点击事件(PC)
private void PC()
{
if (Input.GetMouseButtonDown(0)) // 如果鼠标左键按下
{
RaycastHit hitInfo;
// 射线从鼠标点击处射出
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
Transform targetTransform = null;
// 在maxDistance长度之内,射线ray与第一个对象(无论层级)进行的物理碰撞的信息,存储在hitInfo中;如果有碰撞物体,返回true, 反之false;
if (Physics.Raycast(ray, out hitInfo, Mathf.Infinity, -1))
{
// 获取碰撞到的物体信息
targetTransform = hitInfo.collider.transform;
}
if (targetTransform != null)
{
// DoSomething();
}
}
}
射线点击事件(Mobile)
private void Mobile()
{
// 单指触控
if(Input.touchCount == 1)
{
// 存储触摸点信息
Touch touch = Input.GetTouch(0);
// 如果手指触摸屏幕,但并未移动,不做处理
if(touch.phase == TouchPhase.Stationary)
return;
// 判断是否点击在UI上
if(EventSystem.current.IsPointerOverFameObject(touch.fingerID))
return;
RaycastHit hitInfo;
Ray ray = Camera.main.ScreenPointToRay(touch.position);
Transform targetTransform = null;
if(Physics.Raycast(ray, out hitInfo, Mathf.Infinity, -1))
{
targetTransform = hitInfo.collider.transform;
}
if(targetTransform!= null)
{
// DoSomething();
}
}
}