c# - 如何在 Unity 中使用 OnPointerEnter 区分两个画布文本元素
问题描述
我想区分两个文本元素。如果鼠标悬停其中一个元素,它应该改变文本和位置。我阅读了有关 的文档IPointerEnterHandler
,但无法理解如何在一个脚本中使用画布元素来检测事件IPointerEnterHandler
。
非常感谢帮助。
我的脚本:
public class TextController : MonoBehaviour, IPointerEnterHandler
{
public Text text1;
public Text text2;
public void OnPointerEnter(PointerEventData eventData)
{
if (EnteringText1) // don t know exact if statement
{
text1.text = "i m entering text1";
text1.transform.position = new Vector3(100f, 100f, 0f);
}
else if (EnteringText2) // don t know exact if statement
{
text2.text = "i m entering text2";
text2.transform.position = new Vector3(100f, 100f, 0f);
}
}
}
我在 Unity 中的场景
解决方案
您可以使用EventData.pointerCurrentRaycast.gameObject
获取事件发生的 GameObject 的名称。由于您Text
的游戏对象被命名为text1
and text2
,只需将它们与. 进行比较即可eventData.pointerCurrentRaycast.gameObject.name
。
public Text text1;
public Text text2;
public void OnPointerEnter(PointerEventData eventData)
{
GameObject obj = eventData.pointerCurrentRaycast.gameObject;
if (obj.name == "text1")
{
text1.text = "i m entering text1";
text1.transform.position = new Vector3(100f, 100f, 0f);
}
else if (obj.name == "text2")
{
text2.text = "i m entering text2";
text2.transform.position = new Vector3(100f, 100f, 0f);
}
}
如果您只想比较Text
组件中的值,那么在像我上面那样获取 GameObject 之后,使用GetComponent<Text>()
从中检索Text
它,检查它是否null
在检索其文本值之前Text.text
public void OnPointerEnter(PointerEventData eventData)
{
GameObject obj = eventData.pointerCurrentRaycast.gameObject;
Text text = obj.GetComponent<Text>();
if (text != null)
{
if (text.text == "EnteringText1")
{
text.text = "i m entering text1";
text.transform.position = new Vector3(100f, 100f, 0f);
}
else if (text.text == "EnteringText2")
{
text.text = "i m entering text2";
text.transform.position = new Vector3(100f, 100f, 0f);
}
}
}
笔记:
上面的脚本必须附加到两个Text
组件的父对象,以便它检测其子对象上的事件。在您的情况下,此父对象名为“Canvas”。
推荐阅读
- git - TortoiseGit 日志 - 我可以只查看分支和合并提交吗?
- javascript - 在 Azure 上作为静态应用托管的 Create-react-app 未检测到环境变量
- python - Flask ModelView 未显示在头栏中
- vapor - 如何在 Heroku 和 Vapor4 中设置 HTTP/2
- java - Eclipse 中的 Web 项目缺少“在服务器上运行”选项
- ansible - Ansible - Failed_when 条件如果存在而不是条件
- java - Java - Runtime.getRuntime().exec(command) 的问题
- c++ - 填充和打印 - C++ 中的二维数组
- c# - ClosedXML 使用路径创建现有工作簿会出现异常
- flutter - Flutter googleMap 方向 URL 和 streetView 未在 Android 11 中启动