- Home /
Why does new GUIStyle() give "object reference not set to an instance of an object" error?
I have a GUISkin (buttonGUISkin) initialized in the inspector with a Custom Style named butGUIStyle. I want to create several unique GUIStyle instances using new GUIStyle() repeatedly with the GUIStyle from my GUISkin. I've used this basic structure successfully before. (See one of my other questions for more details) Before I had issues with naming Custom Styles. It seems the last time I updated Unity that problem went away and the Custom style name field can be used. But, now I get 'not set to an instance of an object' when using the same technique I, in fact, am using successfully elsewhere. Here is a code segment that fails, even when using "" as described in my previous question:
using UnityEngine;
using System.Collections;
public class guiskintest : MonoBehaviour {
private GUIStyle[] btnGUIArray;
public GUISkin buttonGUISkin;
private bool firstpass = true;
public int pttcnt=4;
void OnGUI () {
if (firstpass) {
for (int i=0; i<pttcnt; i++) {
btnGUIArray[i] = new GUIStyle(buttonGUISkin.GetStyle("butGUIStyle"));
}
firstpass = false;
}
}
}
Any thoughts on what is going on would be appreiciated!
Are you sure your btnGUIArray is at least 4 units long? And even more, every of those 4 units has a value? Check it, it seems your btnGUIArray has a size of 0 or its values are null.
Hi
What do you exactly pass in your inspector to buttonGUISkin? a GUIStyle or GUISkin?
regards
I just noticed and then saw maddFrogg's comment, too, that I likely forgot to actually initialize the array! Doh! I'll check for sure when I get home, but, that's probably it. I should sleep now and again...;^)
Nerevar, in the inspector buttonGUISkin contains a GUIStyle in the Custom Style section named butGUIStyle.
Answer by wibble82 · Apr 30, 2014 at 05:45 PM
btnGUIArray is null!
inside the if(firstpass), you need to add btnGUIArray = new GUIStyle[pttcnt]
Yep. As I noticed after finally getting 4 hours of sleep and as pointed out by maddFrogg and wibble82, I forgot to initialize the array...;^) Rather than include that in the if(firstpass) I added it in a Start() anticipating what I need to do in the final project:
void Start () {
btnGUIArray = new GUIStyle[pttcnt]; // GUIStyle array for styles from GUI skin
}
Thanks! Now if someone could just provide some insight to my quaternion question...?...;^)