拓展编辑器

前言

今天记录一个比较好用的工具类。
RectExtensions 该类是自定义的静态类,从名字也可以看出其是一个扩展方法类。

正文

准备

开始的时候我们在Assets下创建一个文件夹Editor(Assets -> Editor)我们将扩展方法类写入其中。RectExtensions

开始

接下来是大家喜闻乐见的代码环节。

using UnityEngine;

namespace EditorFramework
{
    
    
    public static class RectExtensions
    {
    
    
        /// <summary>
        /// Rect的扩展方法
        /// </summary>
        /// <param name="self"> 你要拓展的具体是那个类型的方法 </param>
        /// <param name="width">设置的宽度</param>
        /// <param name="padding">内边距</param>
        /// <param name="justMid">仅仅在中间</param>
        /// <returns></returns>
        public static Rect[] VerticalSplit(this Rect self, float width, float padding = 0, bool justMid =true )
        {
    
    
            if (justMid)
            {
    
    
                return new Rect[2]
                {
    
    
                    // 右边 
                    self.CutRight(self.width-width).CutRight(padding).CutRight(-Mathf.CeilToInt(padding/2)),
                    //左边  
                    self.CutLeft(width).CutLeft(padding).CutLeft(-Mathf.CeilToInt(padding/2)),
                };
            }
            //TODO: 不是justMid的情况下对Rect如何计算
            return new Rect[2]
            {
    
    
                new Rect(0, 0, 0, 0),
                new Rect(0, 0, 0, 0)

            };
        }

        /// <summary>
        /// 切掉右边
        /// </summary>
        /// <param name="self">你要拓展的具体是那个类型的方法 </param>
        /// <param name="pixels"> 像素大小 </param>
        /// <returns>rect</returns>
        private static Rect CutRight(this Rect self,float pixels)
        {
    
    
            self.xMax -= pixels;
            return self;

        }
        private static Rect CutLeft(this Rect self,float pixels)
        {
    
    
            self.xMin += pixels;
            return self;

        }
        private static Rect CutTop(this Rect self,float pixels)
        {
    
    
            self.yMin += pixels;
            return self;

        }
        private static Rect CutBottom(this Rect self,float pixels)
        {
    
    
            self.yMax -= pixels;
            return self;
        }
    }
}


使用案例

private void OnGUI()
        {
    
    
            var rect = EditorGUILayout.GetControlRect(GUILayout.Height(20));
            var rects = rect.VerticalSplit(rect.width - 30);
            
            var rectRight = rects[0];
            var rectLeft = rects[1];

            GUI.Label(rectRight,"button");
            if (GUI.Button(rectLeft, GUIContents.Folder))
            {
    
     
                var path = EditorUtility.OpenFolderPanel("打开文件夹", Application.dataPath, "default name");
                m_path = path;
                Debug.Log(Application.dataPath);
            }
}

结尾

这就是是一个拓展编辑器的简单工具类 目的是为了设置一个label和 其他rect组件在同一水平线上

猜你喜欢

转载自blog.csdn.net/m0_52021450/article/details/130030778