0

我有一个画布(世界空间渲染模式),其中一个文本和一个按钮组件显示在三维空间(它是一个 VR 应用程序)中。画布在运行时使用预制件实例化。我使用以下方法获得对 Text 对象的引用:

_codeTextLabel = canvasPrefab.transform.Find("CodeTextLabel").gameObject.GetComponent<Text>();

我想在运行时使用以下方法更新文本:

void Update()
{
    _codeTextLabel.text = _codeText;
}

where_codeText只是我根据特定事件更新的变量。问题是 Text 仅在第一次更新,但如果我尝试更改变量,则没有任何反应。我尝试了几种组合以及方法_codeTextLabel.SetAllDirty(),但它不起作用。

更新文本的唯一方法是重新实例化预制件。

4

2 回答 2

1

Are you instantiating your prefab before setting the values. If you are storing the _codeTextLabel reference before instantiating then your reference will point to the prefab not the runtime object. I can't see the rest of your code, so I can't say for sure. (I would have asked as a comment, but as I'm new I don't have the reputation to do so)

edit: I did a test to try and recreate your problem. I made the following script and it appears to work as expected. CanvasPrefab is a worldspace canvas with a UnityEngine.UI.Text component attached. (The script is attached on an empty game object in the scene btw)

public class ChangeText : MonoBehaviour

    {
        public GameObject CanvasPrefab; 
        private GameObject runtimeCanvas;
        public string runtimeText = "something";
        private Text textRef;
        // Start is called before the first frame update
        void Start()
        {
            runtimeCanvas = GameObject.Instantiate(CanvasPrefab);
            textRef = runtimeCanvas.GetComponentInChildren<Text>();
        }

        // Update is called once per frame
        void Update()
        {
            textRef.text = runtimeText;
        }
    }

于 2019-10-28T00:26:38.620 回答
0
  • 只要你做错了什么,它绝对有效,所以我想有几种情况
    1. 未能执行“_codeTextLabel = canvasPrefab.transform.Find("CodeTextLabel").gameObject.GetComponent();”
    2. '_codeTextLabel' 丢失了来自 'GameObject.
    3. 完全不改变 runtimeText' 的变化
    4. 事件订阅失败我的意思是,您的更新脚本没有获得适当的事件来更新该文本。

没有代码,这是我唯一能猜到的事情,所以请检查上面我希望上面有案例。

于 2019-10-28T04:27:13.250 回答