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で置き換えます)