Unity编辑器开发入门(二)

Unity编辑器   2022-10-23 17:22   955   0  

今天用代码实现编辑器 从Project 复制prefab到 Hierarchy 

用代码实现如下的效果:

33959_1bus_9920.gif

using Sirenix.OdinInspector.Editor;
using Sirenix.Utilities.Editor;
using UnityEditor;
using Sirenix.OdinInspector;
using UnityEngine;


namespace Editor.Tools
{
    public class IndexWindow : OdinMenuEditorWindow
    {
        [MenuItem("MyTools/工作台")]
        private static void OpenWindow()
        {
            IndexWindow window = GetWindow<IndexWindow>();
            window.titleContent = new GUIContent("工作台", EditorIcons.Pen.Active);
            window.Show();
        }

        protected override OdinMenuTree BuildMenuTree()
        {
            OdinMenuTree tree = new OdinMenuTree();
            tree.Add("开发工具", new DevelopWindow());
            return tree;
        }
    }


    public class DevelopWindow
    {
        [Button("复制 wushi.prefab到 Hierarchy", ButtonSizes.Large)]
        [GUIColor("GetButtonColor")]
        public void CopyPrefabFromProject()
        {
            string path = "Assets/Prefab/wushi.prefab";
            GameObject obj = AssetDatabase.LoadAssetAtPath<GameObject>(path);
            GameObject wushi = (GameObject)PrefabUtility.InstantiatePrefab(obj);
            PrefabUtility.UnpackPrefabInstance(wushi, PrefabUnpackMode.Completely, InteractionMode.UserAction);
            EditorUtility.DisplayDialog("系统提示", "复制完成", "我知道了");
        }


        [Button("删除 wushi.prefab从 Hierarchy", ButtonSizes.Large)]
        [GUIColor(0.1f, 0.9f, 0.7f)]
        public void DeletePrefabFromHierarchy()
        {
            GameObject obj = GameObject.Find("wushi");
            Object.DestroyImmediate(obj);
            EditorUtility.DisplayDialog("系统提示", "删除完成", "我知道了");
        }
#if UNITY_EDITOR
        private static Color GetButtonColor()
        {
            GUIHelper.RequestRepaint();
            return Color.HSVToRGB(Mathf.Cos((float)EditorApplication.timeSinceStartup + 1f) * 0.225f + 0.325f, 1, 1);
        }
#endif
    }
}


效果如下:

34221_fwu9_9012.gif

当然,你直接 Instantiate创建,再改名字行不行?实现效果当然可以,但是编辑器开发,还是用编辑器提供的方法更好。

[Button("复制 wushi.prefab到 Hierarchy", ButtonSizes.Large)]
[GUIColor("GetButtonColor")]
 public void InstantiatePrefabFromProject()
        {
            string path = "Assets/Prefab/wushi.prefab";
            GameObject obj = AssetDatabase.LoadAssetAtPath<GameObject>(path);
            GameObject prefab = Object.Instantiate(obj);
            prefab.name = "wushi";
            EditorUtility.DisplayDialog("系统提示", "复制完成", "我知道了");
        }

35035_1rsq_3944.gif

博客评论
还没有人评论,赶紧抢个沙发~
发表评论
说明:请文明发言,共建和谐网络,您的个人信息不会被公开显示。
QQ
微信
打赏
扫一扫