Unity/EditorWindow/GameObjectをPrefabに変更
提供: 初心者エンジニアの簡易メモ
2024年8月11日 (日) 19:57時点におけるAdmin (トーク | 投稿記録)による版 (ページの作成:「==全シーンの、指定したGameObjectをPrefabに変更するコード== <pre> using UnityEditor; using UnityEngine; using UnityEditor.SceneManagement; using UnityEn...」)
全シーンの、指定したGameObjectをPrefabに変更するコード
using UnityEditor; using UnityEngine; using UnityEditor.SceneManagement; using UnityEngine.SceneManagement; using System.IO; public class ReplaceObjectWithPrefab : EditorWindow { private string directoryPath = "Assets/Scenes"; private string objectName = "ReturnButton"; private GameObject prefab; [MenuItem("Tools/Replace Object With Prefab")] public static void ShowWindow() { GetWindow<ReplaceObjectWithPrefab>("Replace Object With Prefab"); } private void OnGUI() { GUILayout.Label("Directory and Object Settings", EditorStyles.boldLabel); directoryPath = EditorGUILayout.TextField("Directory Path", directoryPath); objectName = EditorGUILayout.TextField("Object Name", objectName); prefab = (GameObject)EditorGUILayout.ObjectField("Prefab", prefab, typeof(GameObject), false); if (GUILayout.Button("Replace Objects in Scenes")) { ReplaceObjectsInScenes(); } } private void ReplaceObjectsInScenes() { if (string.IsNullOrEmpty(directoryPath) || string.IsNullOrEmpty(objectName) || prefab == null) { Debug.LogError("Please specify the directory path, object name, and prefab."); return; } // ディレクトリ内のすべてのシーンファイルを取得 string[] sceneFiles = Directory.GetFiles(directoryPath, "*.unity", SearchOption.AllDirectories); foreach (string scenePath in sceneFiles) { // シーンを開く Scene scene = EditorSceneManager.OpenScene(scenePath); if (!scene.IsValid()) { Debug.LogError($"Invalid scene path: {scenePath}"); continue; } // オブジェクトを探す GameObject targetObject = GameObject.Find(objectName); if (targetObject == null) { Debug.LogWarning($"Object '{objectName}' not found in scene: {scenePath}"); continue; } // オブジェクトをプレハブに置き換える GameObject newObject = (GameObject)PrefabUtility.InstantiatePrefab(prefab, scene); newObject.transform.position = targetObject.transform.position; newObject.transform.rotation = targetObject.transform.rotation; // 旧オブジェクトを削除 DestroyImmediate(targetObject); // シーンを保存する EditorSceneManager.MarkSceneDirty(scene); EditorSceneManager.SaveScene(scene); Debug.Log($"Object replaced successfully in scene: {scenePath}"); } } }