- Home /
Question by
WOODSY · Dec 21, 2015 at 09:29 AM ·
scripting problem
Script that works, throws in errors
using UnityEngine;
using System.Collections;
public class NumberPlate : MonoBehaviour {
public string currentName;
GameObject plate;
TextMesh plateText;
void Update()
{
plate = GameObject.FindGameObjectWithTag("NumberPlate");
plateText = plate.GetComponentInChildren<TextMesh>();
plateText.text = currentName;
if (!plate)
return;
if (!plateText)
return;
}
}
At line 14, I get object not set to an instance of an object, but I've saftey checked that with if it's not there it should just return. Any answers would be great!
Comment
Shouldn't you check if plate exists before calling plate.GetComponentInChildren on line 14, because that is where the error is.
Best Answer
Answer by Xarbrough · Dec 21, 2015 at 09:41 AM
A method like Update() is executed line by line. A "safety check" therefore must come before actually using the variable. You simply need to move the if check to line 13.
void Update()
{
plate = GameObject.FindGameObjectWithTag("NumberPlate");
if (!plate)
return;
plateText = plate.GetComponentInChildren<TextMesh>();
if (!plateText)
return;
plateText.text = currentName;
}
}
Answer by WOODSY · Dec 21, 2015 at 06:41 PM
Oh man bow did I miss it! Thank you very much to those who answered! Definitely wasn't thinking last night.
Cheers
Your answer