《Unity 编辑器扩展》通用获取字符串面板

using System;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using static UnityEngine.GUILayout;

 public class GainStringPanel : EditorWindow
    {
        private static List<string> data;
        private Vector2 scrollPos;
        private float itemWidth = 80;
        private float itemHeight = 30;
        private Vector4 padding = new Vector4()
        {
            x = 10,
            y = 10,
            z = 10,
            w = 0,
        };
        private Vector2 space = new Vector2()
        {
            x = 10,
            y = 10
        };
        private static int colCnt = 0;
        private static Action<string> callback;
        public static void Open(List<string> d,Action<string> cb)
        {
            var wnd = GetWindow<GainStringPanel>();
            wnd.name = "ChooseString";
            data = d;
            callback = cb;
        }
        public void OnGUI()
        {
            colCnt = Mathf.FloorToInt((position.width - padding.x - padding.y) / (itemWidth + space.x));
            using(var v = new GUILayout.ScrollViewScope(scrollPos,"OL Box"))
            {
                for (int i = 0; i < data.Count; i++)
                {
                    int row = i / colCnt + 1;
                    int col = i - (row-1)*colCnt + 1;
                    float x = (col - 1) * itemWidth + (col - 1) * space.x;
                    float y = (row - 1) * itemHeight + (row - 1) * space.y;
                    if(GUI.Button(new Rect(x,y,itemWidth,itemHeight),new GUIContent(data[i])))
                    {
                        callback?.Invoke(data[i]);
                        Close();
                    }
                }
            }
            if (Event.current.type == EventType.Repaint)
            {
                Repaint();
            }
        }
    }

《Unity 编辑器扩展》通用获取字符串面板_第1张图片
可以根据窗口的大小自动排序,传入字符串数组,和点击按钮确定字符串后的回调函数可用。

你可能感兴趣的:(unity,编辑器,游戏引擎)