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)

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
}