问题:如图所示,红色方块不能点到哪个九宫格就在哪个九宫格。而是处在屏幕中央产生。
看了很多博客和观察场景,
我发现不是中心在哪方块在哪,
而是取决于我最后点yes的鼠标在哪。
这就说明,鼠标的射线已经穿透我的UI了。因为当时写的代码就是让鼠标选中的九宫格实现yes后产生方块。
解决方法:
1.可以让UI出来的时候停止射线的发射。
2.让射线不能穿透UI
代码:(以下用的是第二个方法)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public EventSystem es;
public Transform changeMatCanvas;
private void Awake()
{
changeMatCanvas = GameObject.Find("Canvas").transform;
}
void Update()
{
//如果射线检测到UI上直接返回
if (EventSystem.current.IsPointerOverGameObject()) return;
}
bool CheckGuiRaycastObjects()
{
PointerEventData eventData = new PointerEventData(es);
eventData.pressPosition = Input.mousePosition;
eventData.position = Input.mousePosition;
List<RaycastResult> list = new List<RaycastResult>();
changeMatCanvas.GetComponent<GraphicRaycaster>().Raycast(eventData, list);
return list.Count > 0;
}
代码非原创!!
然后再给UI所在的图层加一个透明图像,如下图所示:
需要注意:image可以设置为1920x1080,或者更大,要覆盖屏幕;而且image要在最下方,反正要在yes或no的下方,确保能点击yes或no。
做完啦的效果图: