Unity editor development combat [Editor Window] - Replacer

As shown in the figure, if a model is placed in a large number of neatly in the scene, when we modify the model and need to be replaced, it is troublesome to replace the new model one by one according to the above position. The tool Replacer introduced below can be very convenient. for batch replacement:

Select all models to be replaced in the Hierarchy window, then specify the model to be replaced, and click Replace to replace

The tool code is as follows:

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

Guess you like

Origin blog.csdn.net/qq_42139931/article/details/124420780