Advertisement
Pro_Unit

GenericPopupContent

Dec 1st, 2023
807
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.88 KB | None | 0 0
  1. // Example:
  2. // List<Type> items = GetAllSubclasses(typeof(ScriptableObject)).ToList();
  3. // GenericPopupContent<Type>.Show(items, OnScriptableObjectSelected, type => type.Name);
  4. // private void OnScriptableObjectSelected(Type selectedType)
  5. // {
  6. //  _type = selectedType;
  7. //  Repaint();
  8. // }
  9.  
  10. using System;
  11. using System.Collections.Generic;
  12. using System.Linq;
  13.  
  14. using UnityEditor;
  15.  
  16. using UnityEngine;
  17.  
  18. namespace Game.EditorWindows
  19. {
  20.     public class GenericPopupContent<T> : PopupWindowContent
  21.     {
  22.         private string _searchFilter = "";
  23.         private readonly List<T> _items;
  24.         private readonly Action<T> _onSelectCallback;
  25.         private readonly Func<T, string> _nameSelector;
  26.  
  27.         private Vector2 _scrollView;
  28.  
  29.         private GenericPopupContent(List<T> items, Action<T> onSelect, Func<T, string> nameSelector = default)
  30.         {
  31.             _nameSelector = nameSelector ?? (t => t.ToString());
  32.             _items = items;
  33.             _onSelectCallback = onSelect;
  34.         }
  35.  
  36.         public static void Show(List<T> items, Action<T> onSelect, Func<T, string> nameSelector = default)
  37.         {
  38.             var content = new GenericPopupContent<T>(items, onSelect, nameSelector);
  39.  
  40.             PopupWindow.Show(new Rect(Event.current.mousePosition, Vector2.zero), content);
  41.         }
  42.  
  43.         public override void OnGUI(Rect rect)
  44.         {
  45.             EditorGUILayout.Space();
  46.             _searchFilter = EditorGUILayout.TextField(_searchFilter, (GUIStyle)"SearchTextField");
  47.             EditorGUILayout.Space();
  48.  
  49.             _scrollView = EditorGUILayout.BeginScrollView(_scrollView);
  50.  
  51.             IEnumerable<T> query = from item in _items
  52.                 let itemName = _nameSelector(item)
  53.                 where Contains(itemName)
  54.                 where GUILayout.Button(itemName)
  55.                 select item;
  56.  
  57.             foreach(T item in query)
  58.             {
  59.                 _onSelectCallback?.Invoke(item);
  60.                 editorWindow.Close();
  61.             }
  62.  
  63.             EditorGUILayout.EndScrollView();
  64.         }
  65.  
  66.         private bool Contains(string itemName) => itemName.ToLower().Contains(_searchFilter.ToLower());
  67.     }
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement