How do I nullreference this correctly?

Hello! I am playing around with some dialogue-scripting from the ground up. And I am having a bit of an issue with nullreferencing something that isn’t active.

So this is the code that will check for a gameobject:

		GameObject textInBubble = GameObject.Find ("TextInBubble");
		TextMesh textMeshThing = (TextMesh)textInBubble.GetComponent(typeof(TextMesh));

The thing is, that what this code wants to find is on standard set to be inactive. It only becomes active when a dialogue is occurring, and on and off relative to the conversation in question.

I know I could force this code to work if I paste it in everytime I actually state that this gameObject is active, which would look something like this:

			if(i == 0){
				speechBubbleActive = true;
				GameObject textInBubble = GameObject.Find ("TextInBubble");
				TextMesh textMeshThing = (TextMesh)textInBubble.GetComponent(typeof(TextMesh));
				textMeshThing.text = "Hello Unity Community!";
			}
			else{speechBubbleActive = false;}

Obviously, this is unwanted behavior, it would create a mass amount of duplicate entries in my code…

There has to be a way to do checks every frame. With a correct nullreference when the gameobject is not active. Any help or direction is appreciated. I tried finding it out by my own but I have had no luck so far. Thanks!

if you’re setting flags when it’s in/active then checking that before attempting to check the component would work, but you should null check after every component get/find/etc.

if (speechBubbleActive)
{
    GameObject textInBubble = GameObject.Find ("TextInBubble");
    if (textInBubble != null)
    {
        TextMesh textMeshThing = textInBubble.GetComponent<TextMesh>();
        if (textMeshThing != null)
        {
            textMeshThing.text = "Hello Unity Community!";
        }
    }
}

ideally, you’d get these references in Start()/Awake() to save having to do it every time, then you just need the null check…