Skip to content

Instantly share code, notes, and snippets.

@rje
Last active January 20, 2019 00:23
Show Gist options
  • Save rje/c2e2f60c4b20bf8f6fcbe76cf4844fe6 to your computer and use it in GitHub Desktop.
Save rje/c2e2f60c4b20bf8f6fcbe76cf4844fe6 to your computer and use it in GitHub Desktop.
// The returned Vector2 is the updated scroll position of the scroll area
// scrollPos is the current scroll position
// objects is the list of prefabs to draw in the palette
// selectionCheck is a lambda to check if a given object is the currently selected one, e.g. (go) => go == _currentSelection
// setSelection is a lambda to set the current selection, e.g. (go) => _currentSelection = go
Vector2 DrawScrollingPalette(Vector2 scrollPos, List<GameObject> objects, Func<GameObject, bool> selectionCheck, Action<GameObject> setSelection)
{
var scope = new EditorGUILayout.ScrollViewScope(scrollPos, false, true, GUILayout.Height(300));
var needsEnd = false;
using (scope)
{
// we are currently hardcoded to have rows of 4, to change we'd need to update where we check this index for 0 & 3 to be
// whatever we want
var idx = 0;
foreach (var obj in objects)
{
if (idx == 0)
{
GUILayout.BeginHorizontal();
needsEnd = true;
}
// This is the call to actually get the preview texture. If you have lots of objects you might need to call
// AssetPreview.SetPreviewTextureCacheSize() and set a higher value
var preview = AssetPreview.GetAssetPreview(obj);
var rect = GUILayoutUtility.GetRect(60, 60);
if (Event.current.type == EventType.MouseDown)
{
var pos = Event.current.mousePosition;
if (rect.Contains(pos))
{
setSelection(obj);
Event.current.Use();
}
}
if (preview != null)
{
EditorGUI.DrawPreviewTexture(rect, preview);
}
if (selectionCheck(obj))
{
EditorGUI.DrawRect(rect, new Color(1, 1, 1, 0.2f));
}
// if we're at the end of the row, close it up
if (idx == 3)
{
GUILayout.EndHorizontal();
needsEnd = false;
}
idx = (idx + 1) % 4;
}
// if we ended with a partial row, fill it with flexible space and close it out
if (needsEnd)
{
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
}
}
return scope.scrollPosition;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment