- Home /
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!
Answer by gjf · Dec 05, 2014 at 01:25 PM
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...
I'm trying out this thing in start method right now, I just remembered that it might work, haha. check with you later
Just remembered I could do this in my Start() method, and it worked fine when doing my checks:
void Start() {
speechBubble = GameObject.Find ("SpeechBubbleJohn");
textInBubble = GameObject.Find ("TextInBubble");
text$$anonymous$$eshThing = (Text$$anonymous$$esh)textInBubble.GetComponent(typeof(Text$$anonymous$$esh));
}
Your answer
Follow this Question
Related Questions
node null reference 1 Answer
Setting Prefab with Code Returns NULL 2 Answers
Simple Looping drag and drop game 1 Answer
Instantiate gameObject returns null? 1 Answer