使用 PointerEnter 动态更改文本

Change a Text dynamically using PointerEnter

由于我目前正在开发基于 Unity 引擎的游戏,因此我需要一个 PointerEnter EventTrigger 来动态更改我的文本。具体来说:

如果用户将鼠标悬停在 MainMenu 中的文本上,我需要一个指示符,指示他指向的是哪个选项。 因此,从 Options 开始,文本应变为 ▶ Options

我所做的是:

Text text;
string ContinueText = "▶ Continue";

void Awake()
{
    // Set up the reference.
     text = GetComponent<Text>();
}
    public void Test()
{
    text.text = ContinueText;
}

但是如果我将鼠标悬停在文本上,我会得到

NullReferenceException: Object reference not set to an instance of an object

指向text.text = ContinueText;

所以我在网上搜索了一下,发现void Update()有时会在Awake()之前被调用,反正Error还是一样。 Canvas-文本名为 "Text_Options",以备不时之需。

谢谢你帮我!

这是一个工作示例。

一个 canvas 带有一个空游戏对象(有一个垂直布局组,但那不相关),它是两个文本对象的容器。

我分别添加了两个事件触发器,OnPointerEnter 和 OnPointerExit。两个文本对象上都有我的脚本 HoverText

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class HoverText : MonoBehaviour
{
    Text text;
    public string content = "Text A";
    public string contentHighlighted = "▶ Text A";

    void Awake()
    {
        text = GetComponent<Text>();
        text.text = content;
    }

    public void Highlight()
    {
        text.text = contentHighlighted;
    }

    public void UnHighlight()
    {
        text.text = content;
    }
}

Text_A 将自己作为游戏对象,因为它分别是事件触发器和 Text_B 本身。两个不同文本内容的 public 字符串是通过检查器设置的(在我的示例中,脚本的默认值实际上匹配 Text_A)。

就是这样,工作正常。