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

这是一个Unity编辑器的扩展脚本,创建了一个可以自适应窗口大小的字符串列表选择面板。用户能够通过点击按钮从列表中选择一个字符串,并在选择后调用指定的回调函数。此脚本使用GUILayout布局系统实现滚动视图,支持多列显示和窗口关闭功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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();
            }
        }
    }

在这里插入图片描述
可以根据窗口的大小自动排序,传入字符串数组,和点击按钮确定字符串后的回调函数可用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JustEasyCode

谢谢您

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值