c# - Unity 中 set active 和 Input.touch 中的故障
问题描述
我有一个应用程序可以在用户点击时生成模型,当用户点击模型时,会弹出一个菜单。
当用户点击除画布元素之外的任何其他位置时,菜单将关闭。
但这不起作用,当我按下画布元素时,它会检测到画布元素,但菜单仍然关闭。
这是我的代码:
void Update()
{
UpdatePlacementPose();
UpdatePlacementIndicator();
if (Input.touchCount > 0 )//&& Input.GetTouch(0).phase == TouchPhase.Began)
{
Ray ray = Camera.main.ScreenPointToRay(Input.GetTouch(0).position);
RaycastHit hit;
debugText.text = "touched";
// Check if finger is over a UI element
if (EventSystem.current.IsPointerOverGameObject(Input.GetTouch(0).fingerId))
{
Debug.Log("Touched the UI");
debugText1.text = "Touched the UI";
isui = true;
}
else
{
isui = false;
if (Physics.Raycast(ray, out hit) && (hit.transform.name != "Quad"))
{
//debugText.text = hit.transform.name;
debugText.text = Input.touchCount.ToString();
if (IsSpawned)
{
debugText1.text = ColourImage.activeSelf.ToString();
ColourImage.SetActive(true);
//debugText.text = objectToPlace.name;
}
}
else
{
if (placementPoseIsValid && Input.touchCount > 0 && !IsSpawned)
{
PlaceObject();
IsSpawned = true;
PlayerPrefs.SetString("type", "medium");
}
else
{
ColourImage.SetActive(false);
}
}
}
}
//if (placementPoseIsValid && Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
//{
// PlaceObject();
//}
}
解决方案
您可以使用GraphicRaycaster
来测试点击事件是否针对 UI 元素。
这是一个简单的演示来给出这个想法
public class Demo : MonoBehaviour
{
#pragma warning disable 0649
[SerializeField] private EventSystem _eventSystem;
[SerializeField] private GraphicRaycaster _graphicRaycaster;
#pragma warning restore 0649
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
if (TestClickEvent(Input.mousePosition))
{
Debug.Log("Clicked UI Element");
}
}
}
private bool TestClickEvent(Vector3 mousePos)
{
PointerEventData data = new PointerEventData(_eventSystem);
data.position = mousePos;
List<RaycastResult> results = new List<RaycastResult>();
_graphicRaycaster.Raycast(data, results);
if(results.Count > 0)
{
//You can loop through the results to test for a specific UI element
return true;
}
return false;
}
}
更多信息参见官方文档
推荐阅读
- angular - Angular 2+:我可以让吸气剂出现在我的 POST 正文中吗?
- r - model.frame.default 中的错误与 R 中的预测
- reactjs - React Dropzone Uploader 在放置时提交文件,而不是在我单击提交时提交
- android - imeOptions="actionNext" 不会移动到下一个 EditText 而是聚焦
- unity3d - Google Play 应用被拒绝 - 特殊限制:增强现实
- cucumberjs - 黄瓜 js > 7 - junit 格式化程序
- javascript - 滚动垂直时如何滚动水平列表
- git - 我使用两个 GitHub 帐户。如何自定义我的 posh-git 或 PowerShell 以便它始终显示当前登录的 git 用户名?
- reactjs - 如何正确地将数组接口/类型传递给 TypeScript React 中的子组件?
- python - 在不使用像素的情况下模拟特定元素(对于应用程序)的滑动