NullReferenceException but script still works???

Hi,

i’m getting ‘NullReferenceException’ but the script still works.

using UnityEngine;
using System.Collections;

public class centerShowHide : MonoBehaviour {

	private GUITexture gt;
	
	// Use this for initialization
	void Start () {
		
		gt = (GUITexture)gameObject.GetComponent("GUITexture");
		gt.pixelInset = new Rect( -(gt.pixelInset.width/2.0f), -(gt.pixelInset.height/2.0f), gt.pixelInset.width, gt.pixelInset.height );
	
	}
	
	// Update is called once per frame
	void Update () {

	}
	
	// Show GUITexture
	public void show() {
	
		gt.enabled = true;
		
	}
	
	// Hide GUITexture
	public void hide() {
		
		gt.enabled = false;
		
	}
}

The last function hide gives it.

Although i can work with this, it would be nice to know if i’m doing something wrong.

I’m calling the show and hide functions from another script.

centerShowHide CSH_Script = (centerShowHide)GameObject.Find("label_1").GetComponent("centerShowHide");

And the usage:

CSH_Script.show();

or

CSH_Script.hide();

Thanks in advance …

I’m guessing: you try to use show and hide during start, is that possible?
In that case you actually might run into it because the other component has not run yet.

To solve that, you could move the initialization from the centerShowHide to its Awake function.
Awake functions for all objects in a scene at startup are called through before the first object will have the start function called.

If you retry the show / hide at later points it won’t throw the error anymore and work.

Thanks dreamora that solved the problem!

I used the Awake() instead of Start(). I was’nt aware of that function … :smile: