Can you select a GUILayout.Box?

I am creating a ‘simple’ level editor. In the editor window I am displaying assetpreviews from a specific folder. This works fine.

Currently the only way I can check if one of these preview is selected is by using a button.
I would like to style the editor a bit more and use something else instead, making it more akin the asset browser.

Is it possible to have a selected GUILayout.Box at all (if so I am doing something wrong).
Or should I try/do something else?

-PIeter

Yes, it’s possible. You have to seperate an GUI element into two parts:

  • functional
  • visual

Those two things are actually very loosely coupled. The functional part is selected depending on which element function you call. A GUILayout.Box is a passive element like Label. It doesn’t have any interactions with the user. However you can use any GUIStyle to actually draw any GUI element.

When you say you want to “select” an element you need that functionality in the first place. You could use a Toggle or If you only need a single item selected and want a grid pattern you can use a SelectionGrid.

Each of those element functions has a style parameter, some have even multiple like scrollbars. Unity implicitly can convert strings into GUIStyles by using the current active GUISkin. So for example you can draw a Toggle with the label style. That way the Toggle looks exactly like a Label but actually is a Toggle:

// C#
bool b1, b2;

b1 = GUILayout.Toggle(b1, "Click Me", "label");
b2 = GUILayout.Toggle(b2, "Click Me", "box");

You can also use “box” or “button”. Note: Each GUIStyle can have different “state” textures. The default Label style doesn’t have a special “active” style so when an element is selected that state won’t be reflected by the visuals.

It’s best to actually create your own GUISkin, make it active in your code and define your own GUIStyle with your own textures.

For more information see my GUI crash course.