0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Unity】Editorでシーン上のオブジェクトを一括で置き換え方法

Last updated at Posted at 2024-07-18
ReplaceMono.cs
using UnityEngine;
using UnityEditor;

public class ReplaceMono : MonoBehaviour
{
    public Transform LookRoot;
    public GameObject NewObj;
    public string matchName;
}

#if UNITY_EDITOR
[CustomEditor(typeof(ReplaceMono))]
// 継承クラスは Editor を設定する
public class ReplaceObjectEditor : Editor
{
    // parent直下の子オブジェクトをforループで取得する
    private static Transform[] GetChildren(Transform parent)
    {
        var ctransforms = parent.GetComponentsInChildren<Transform>();
        return ctransforms;
    }

    // GUIの表示関数をオーバーライドする
    public override void OnInspectorGUI()
    {
        // 元のインスペクター部分を表示
        base.OnInspectorGUI();

        // targetを変換して対象スクリプトの参照を取得する
        ReplaceMono tg = target as ReplaceMono;

        // public関数を実行するボタンの作成
        if (GUILayout.Button("Replace Object"))
        {
            Transform rootGOs = tg.LookRoot;
            var rootG = GetChildren(rootGOs);
            foreach (var n in rootG)
            {
                if (n.name.IndexOf(tg.matchName) != -1)
                {
                    var parent = n.parent;
                    var pos = n.position;
                    var name = n.name;

                    var newObj = UnityEditor.PrefabUtility.InstantiatePrefab(tg.NewObj, parent) as GameObject;
                    newObj.transform.position = pos;
                    newObj.name = name;

                    GameObject.DestroyImmediate(n.gameObject);
                }
            }
        }
    }
}
#endif

使用方法:
1.「ReplaceMono.cs」を適当にどこかのゲームオブジェクトにアタッチします。
2.インスペクタでチェックしたいゲームジェクトを設置し、「Replace Object」ボタンを押下します。
3.下記の画像は参考になります。(シーン内のCubeを別のスクリプトアタッチしたCubeで置き換えます)

元シーン、普通のCubeを三つで置く:
スクリーンショット 2024-07-18 12.50.14.png
置き換えしたいCubeのプレハブ作成:
スクリーンショット 2024-07-18 12.49.42.png
結果:
スクリーンショット 2024-07-18 12.50.39.png

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?