与Unity中的自定义UI元素进行交互 [英] Interact with custom UI element in Unity
问题描述
我在与自定义UI元素交互时遇到问题.我有一个自定义模式窗口,当我将鼠标悬停在对象上时会显示该窗口,然后当鼠标离开模式窗口区域时我想将其消失,但是我找不到解决方法. 层次结构和画布检查器中的游戏对象
I have problem interact with custom UI element. I have a custom modal window which is displayed when I hover mouse over the object and then I want to disappear it when mouse leaves modal window area but I can't find solution how to do it. Game Objects in the hierarchy and canvas inspector
我在互联网上进行搜索,尝试过使用raycasters,但是它无法正常工作,或者我做错了事.
I searched on the internet, I tried it with raycasters but its not working or maybe I doing something wrong.
这是我将鼠标悬停在对象上时如何调用Script ModalWindowScript的方式,以便我可以以某种方式与UI元素进行交互.
This is how I call Script ModalWindowScript when is mouse over object so I can somehow interact with UI elements.
[SerializeField] GameObject uIModalWindow;
private void Start()
{
uIModalWindow.SetActive(false);
}
private void OnMouseEnter()
{
var mousePos = Input.mousePosition;
Debug.Log(gameObject.name);
uIModalWindow.transform.position = mousePos;
uIModalWindow.SetActive(true);
}
private void OnMouseExit()
{
uIModalWindow.AddComponent<ModalWindowScript>();
}
预期结果是,当鼠标离开模态窗口区域时,模态窗口将消失.但是实际状态是我无法找到如何与UI进行通信.
Expected result is that modal window will disappear when mouse will leave the modal window area. But actual status is that I can't find out how to communicate with UI.
HoverOverObject ModalWindowScript
推荐答案
您需要实现IPointerEnterHandler& IPointerExitHandler接口可获取此类解决方案以获取适当的事件:
You need to implement the IPointerEnterHandler & IPointerExitHandler interface to get this kind of solution to get the proper events:
public class HoverOverObject : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler
[SerializeField] GameObject uIModalWindow;
private void Start()
{
uIModalWindow.SetActive(false);
}
public void OnPointerEnter(PointerEventData e)
{
var mousePos = Input.mousePosition;
Debug.Log(gameObject.name);
uIModalWindow.transform.position = mousePos;
uIModalWindow.SetActive(true);
}
public void OnPointerExit(PointerEventData e)
{
uIModalWindow.AddComponent<ModalWindowScript>();
}
}
注意更改的代码:添加了接口,更改了方法的名称,将方法的可访问性从私有更改为公共.
Note changed code: Added Interfaces, Changed name of methods, Changed accessibility from private to public on methods.
这篇关于与Unity中的自定义UI元素进行交互的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!