Error on GUIStyle.Draw


I’m seeing this error when rendering a custom list box class.

Style.Draw may not be called if it is not a repaint event
UnityEngine.GUIStyle:Draw(Rect, GUIContent, Boolean, Boolean, Boolean, Boolean)
GameObjectListItem:DrawItem(Rect, GUIStyle, Boolean) (at Assets/GameAssets/UX/Core/GameObjectListBox.cs:199)
GameObjectListBox:OnGUI() (at Assets/GameAssets/UX/Core/GameObjectListBox.cs:88)

It is drawing the individual elements, but it’s also throwing this error what looks to be every other OnGUI.

The list box class inherits from MonoBehavior and implements OnGUI and inside that it iterates through the individual items and calls the above DrawItem method. The individual list box items are not MonoBehavior items and don’t implement OnGUI.

Any ideas? Do I need to redesign so the individual items inherit from monobehavior?

It doesn’t matter where your code is located. It can be in any kind of function event of a different script. The important thing is that it’s always called from within a OnGUI function. You can’t use GUI stuff outside a OnGUI function but as long as you call your functions from OnGUI in ok.

Your problem have nothing to do with the location of your code. That’s a bit tricky and not that obvious when you work with it the first time.
OnGUI is called several times per frame! The Event class is the big brother of OnGUI. Event.current holds the current instance and Event.current.type specifies the reason why OnGUI has been called.

There are two EventTypes that fires always each frame:

The first one can be disabled with MonoBehaviour.useGUILayout for a single script which doesn’t want to use GUILayout stuff

There are other events for all sorts of input messages (mouse, keyboard). The utility functions that comes with Unity like GUI.Button() checks internally what’s the current event and do different things. OnKeyUp the button have to react to the input and might return true when the cursor is within it’s rectangle. All drawing however can only be done in the repaint event.

When you use GUIStyle.Draw manually in OnGUI you have to make sure that it’s only called in the repaint step:

if (Event.current.type == EventType.Repaint)

There can be a Button in your hierarchy that has a missing script in its onClick and your Button can want to access to it