Hi guys
Having a problem updating text in a TextMeshPro prefab at runtime.
I have no problem instantiating it. On my prefab I also have the following component which always throws a NullReferenceException error.
Can anyone tell me what I am doing wrong?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using TMPro;
public class ThoughtBubble : MonoBehaviour {
private TMP_Text _tmPro;
void Start ()
{
_tmPro = GetComponent(typeof(TMP_Text)) as TMP_Text;
}
public void TextUpdate( string info) {
//following gives NullReferenceException: Object reference not set to an instance of an object
_tmPro.text = info;
}
}
My guess is that you are instantiating the prefab and then immediately calling TextUpdate() on it from the same function. It will be null because the object’s Start() function hasn’t been run yet. You’ll either need to wait a frame, or reorganize your code so that it doesn’t rely on Start() having already been called.
Incidentally, you may want to get in the habit of using
GetComponent<TMP_Text>()
instead of
GetComponent(typeof(TMP_Text)) as TMP_Text
both for efficiency reasons and because it’s less typing.
Yep thanks
Changed from Start to Awake and good to go
Still not sure of the exact context, but I doubt using Awake will fix your problem.
Generally speaking, Unity is not going to interrupt the function that’s already running in order to call a routine function like Start or Update; it will wait until you’re done with whatever you’re already in the middle of doing.
I generally address this sort of issue by putting a flag in the class to track whether it’s been initialized (and then performing initialization in any function that needs it if it hasn’t been done yet) or refactoring the code so that separate initialization isn’t required.