- Home /
How to use GUIStyles in OnInspectorGUI?
Hello - I'm trying to use a very simple GUIStyle for a label in my custom editor. However, when I use it I get all sorts of errors, ArgumentExceptions, NullReferneces, Can't use/call GUI stuff outside of OnGUI, etc.
How can I create a GUIStyle for my editor elements?
Here's what I'm doing:
private readonly GUIStyle StatesLabel = new GUIStyle(GUI.skin.label)
{
alignment = TextAnchor.MiddleLeft,
margin = new RectOffset(),
padding = new RectOffset(),
fontSize = 15,
fontStyle = FontStyle.Bold
};
Using it like:
GUILayout.Label("States", StatesLabel);
Thanks for any help.
EDIT:
Alright it seems that the errors go away if I remove the GUI.skin.label from the GUIStyle constructor. - But if I do so, how can I then create styles for buttons, labels, toggles, etc?
It seems that I can't do anything "GUI"ish in OnInspectorGUI? (can't even do a GUI.backgroundColor change... - very frustrated)
Answer by Bunny83 · Feb 01, 2014 at 02:13 AM
The problem is that GUI.skin, which is a property, can only be accessed inside OnGUI / OnInspectorGUI, like the error tells you. So you have to move the initialization to OnInspectorGUI:
private bool initDone = false;
private GUIStyle StatesLabel;
void InitStyles()
{
initDone = true;
StatesLabel = new GUIStyle(GUI.skin.label)
{
alignment = TextAnchor.MiddleLeft,
margin = new RectOffset(),
padding = new RectOffset(),
fontSize = 15,
fontStyle = FontStyle.Bold
};
}
void OnInspectorGUI()
{
if (!initDone)
InitStyles();
// your GUI code
}
THAN$$anonymous$$ YOU!!!!!!! - However, any idea why am I not getting a "Button"y look after using a GUI.skin.button to construct a style?
What I'm doing:
UtilButton = new GUIStyle(GUI.skin.button)
{
alignment = TextAnchor.$$anonymous$$iddleCenter,
fontSize = 20,
padding = new RectOffset()
};
if (GUILayout.Button("▼", UtilButton, GUILayout.Width(20)))
states.$$anonymous$$oveElementDown(i);
What I'm getting (doesn't look like a button :/) :
Even if use a GUI.Button
and pass the style there - it still doesn't look like a button - any ideas?
If I don't use the style however, I get a buttony like thing - eventhough I'm telling it to use the default style (GUI.skin.button)
Seems that I can't use the default GUI stuff in OnInspectorGUI?
Tried constructing with "EditorStyles.$$anonymous$$iButton" - still no button shape =(
Your answer
Follow this Question
Related Questions
GUI works fine in editor, but not in build 2 Answers
Optimizing OnGUI - Too many gui elements? 2 Answers
Setting up GUIStyles, best practice. 1 Answer
Access custom style from skin via string 1 Answer
OnGui Function help 1 Answer