- Home /
NullReferenceException
Hi. I am completely lost on this, and I've been trying to find a previously answered question, but none of them really fits my application. I am not entirely sure how I'm getting this error. I am trying to make my script that is in a separate GameObject control a GUIText.
I'm trying to connect the empty Game Manager GameObject to the "InfoText" TextGUI that is highlighted.
Please help me clean up this script. (I prefer UnityScript/JavaScript thank you.)
private var InfoText : GUIText;
function Awake(){
var InfoText = GameObject.Find("/Building Mode GUIs").guiText;
InfoText = gameObject.GetComponent("Text").guiText;
}
function Update(){
InfoText.text = "Total Cost: " + PriceAdding;
Error Message :
NullReferenceException: Object reference not set to an instance of an object
Game Manager.Awake () (at Assets/Game Manager.js:16)
Answer by PAHeartBeat · Dec 03, 2014 at 04:58 AM
Hi
In line 4 you alread take GUI Componanet in "InfoText" variable so yo don't need line 5 just remove it but your line 4 is also wrong as per your screen shot
In screen shot you have "GUI Text" component on GameObject "InfoText"
"InfoText" GameObject is Child of "Building Mode GUIs"
so your code should like this
var InfoText = GameObject.Find("Building Mode GUIs/InfoText");
var myGuiText : GUIText;
if(InfoText) {
myGuiText = InfoText.GetComponent<GUIText>();
}
if(myGuiText) {
myGuiText.text = "value";
}
Answer by robertbu · Dec 02, 2014 at 05:24 AM
GUIText is not of type Text. Avoid using the string version of GetComponent() Assuming your GameObject.Find() is succeeding and the game object has a GUIText component, then delete line 5. Line 4 should work to get access to the GUIText component.
Answer by JA_555 · Dec 03, 2014 at 09:23 AM
Perhaps you could try:
private var InfoText : Text;
function Awake(){
InfoText = GameObject.Find("/Building Mode GUIs").text
}
function Update(){
InfoText.text = "Total Cost: " + PriceAdding;
I think you just confused your GUIText and text.
This is very unstable as you do not check for null values - if the Find method returns null, a null pointer exception will be thrown on Awake and also every update call.