Problem in initialising Texture2D array of GUI images dynamically.

Dear Folks,

I am currently designing the GUI of my 3D game. I just want to show countdown images like 2->1->0 on the screen. To implement this I have written a script which first initialises an array of 2D images in Awake() function, then in the OnGUI() method I just tried to display this image array via incrementing the array index. But in OnGUI() I am getting null reference exception.

My code looks like this:

void Awake() {
		Texture2D[] countdown_anim = new Texture2D[3];
		countdown_anim[0] = Resources.Load("HUD/countdown/Counter2") as Texture2D;
		countdown_anim[1] = Resources.Load("HUD/countdown/Counter1") as Texture2D;
		countdown_anim[2] = Resources.Load("HUD/countdown/Counter0") as Texture2D;
}

void OnGUI() {
GUI.skin = newSkin;

if(w < countdown_anim[0].width)  // getting NULL Reference Exception Here onwards
     w+=(countdown_anim[0].width/countdown_anim[0].height)*10;
else
     w=countdown_anim[0].width;
if(h < countdown_anim[0].height)
	h+=10;
else
	h=countdown_anim[0].height;
			
GUI.DrawTexture(new Rect((Screen.width-w)/2, (Screen.height-h)/2, w, h), countdown_anim[countdown]);

if(countdown <= 2)
    countdown++; //in order to display next array element
}

Moreover, i tried to access countdown_anim[0].width countdown_anim[0].height from Awake() method also, then I can successfully access the values, but it gives error inside OnGUI() method of the same script.

It may be possible that my Texture2D array is not properly initialised. Please guide me how to resolve this.

Looking for an early reply.

Regards,
Atul

I think you need to include the file extension for your image names

As the docs say, “extensions must be omitted”.

–Eric

true that of coarse , sorry was obviously not thinking with the correct part of my brain.

Looking at the code again all that can be at fault is that the path to resource is incorrect or the “w” field is not declared?

youre declaring Texture2D[ ] countdown_anim = new Texture2D[3]; in awake. You need to make a class variable to access them in the other functions.

Thanks a lot to all of you. I have figured out the problem, actually the suggestion of @PAEvenson helped me in resolving this.