Unity 编辑器开发实战【Editor Window】- Replacer 替换器

2022-08-29 17:02:58 浏览数 (3)

如图所示,假如一个模型被大量的规整的摆放在场景中,当我们修改了这个模型需要替换时,需要将新模型按照如上位置进行逐个替换比较麻烦,下面介绍的工具Replacer可以很方便的进行批量替换:

在Hierarchy层级窗口选中所有需要替换的模型,然后指定用来替换的模型,点击Replace进行替换

工具代码如下:

代码语言:javascript复制
using UnityEditor;
using UnityEngine;

namespace SK.Framework
{
    /// <summary>
    /// 替换器
    /// </summary>
    public class Replacer : EditorWindow
    {
        [MenuItem("SKFramework/Replacer")]
        public static void Open()
        {
            var window = GetWindow<Replacer>("Replacer");
            window.maxSize = new Vector2(300f, 60f);
            window.minSize = new Vector2(300f, 60f);
            window.Show();
        }
        //用于替换的物体
        private GameObject target;

        private void OnGUI()
        {
            int count = Selection.gameObjects.Length;
            GUILayout.Label(string.Format("Count: {0}", count));

            GUILayout.BeginHorizontal();
            GUILayout.Label("Replacer:", GUILayout.Width(100f));
            target = EditorGUILayout.ObjectField(target, typeof(GameObject), true) as GameObject;
            GUILayout.EndHorizontal();

            GUI.enabled = target != null;
            if (GUILayout.Button("Replace"))
            {
                //弹窗提醒
                if (EditorUtility.DisplayDialog("提醒", string.Format("将使用{0}替换所有选中的物体,是否确认?", target.name), "确认", "取消"))
                {
                    //遍历
                    for (int i = 0; i < Selection.gameObjects.Length; i  )
                    {
                        var go = Selection.gameObjects[i];
                        //实例化
                        var instance = Instantiate(target);
                        instance.transform.position = go.transform.position;
                        instance.transform.rotation = go.transform.rotation;
                        instance.transform.SetParent(go.transform.parent);
                        //销毁
                        DestroyImmediate(go.gameObject);
                        i--;
                    }
                }
            }
        }

        private void OnSelectionChange()
        {
            Repaint();
        }
    }
}

0 人点赞