0
votes

I have a Canvas (World Space Render mode) with a Text and a Button component displayed in a tridimensional space (it's a VR app). The canvas instantiated at runtime using a prefab. I get a reference to the Text object using:

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

I want to update the text at run-time using:

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

where _codeText is just a variable I update based on specific events. The problem is that the Text gets updated only the first time, but if I try to change the variable nothing happens. I have tried several combinations and also the method _codeTextLabel.SetAllDirty() but it doesn't work.

The only way to update the text is to re-instantiate the prefab.

2
Please include the entire class, so it is easier for us to debug.Draco18s no longer trusts SE

2 Answers

1
votes

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;
        }
    }

0
votes
  • as long as you did something wrong, It works absolutely so I guess there are several cases
    1. Failed to do "_codeTextLabel = canvasPrefab.transform.Find("CodeTextLabel").gameObject.GetComponent();"
    2. '_codeTextLabel' lost reference from 'GameObject.
    3. Doesn't change runtimeText' change at all
    4. Subscription of events failed I mean, your updating scripts doesn't get proper event to update that text.

Without codes, this is only thing I can guess for yours so please check above I hope there is case among above.