Unity 实用教程之 移动端PC端区分点击在UI非UI
1、在Unity引擎上新建一个空工程,具体如下图

2、在场景中添加一个 Image 和 Text,布局效果如下图


3、在工程中新建一个脚本 UIEventSysytem,双击打开脚本进行编辑,具体如下图

4、UIEventSysytem 脚本的具体代码和代码说明如下图

5、UIEventSysytem 脚本的具体内容如下:
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class UIEventSystem : MonoBehaviour {
public Text text;
// Update is called once per frame
void Update () {
//关键是要区分移动端和电脑端
//因为移动端和电脑端判断的条件不同
if (Input.GetMouseButtonDown(0)) {
#if UNITY_ANDROID || UNITY_IPHONE
//移动端判断如下
if (EventSystem.current.IsPointerOverGameObject(Input.GetTouch(0).fingerId))
#else
//PC端判断如下
if (EventSystem.current.IsPointerOverGameObject())
#endif
{
text.text = "点击在UI上";
}
else {
text.text = "点击不在UI上";
}
}
}
}
6、脚本编译正确,回到Unity,新建一个 GameObject,脚本挂载上去,把场景中的 Text赋给脚本,具体如下图

7、运行场景,点击 UI和不在UI上效果具体如下图,你也可以打包到 移动端测试,效果如下图
