首页 > 解决方案 > 如何在 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 中的场景

在此处输入图像描述

标签: c#unity3d

解决方案


您可以使用EventData.pointerCurrentRaycast.gameObject获取事件发生的 GameObject 的名称。由于您Text的游戏对象被命名为text1and 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”。


推荐阅读