Created
June 26, 2018 11:05
-
-
Save paulsinnett/8ea823578f1033f6916515b8fe68cfc0 to your computer and use it in GitHub Desktop.
Replace objects with a prefab
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEditor; | |
using UnityEngine; | |
public class ReplaceWithPrefabWindow : EditorWindow | |
{ | |
public Transform prefab; | |
[MenuItem("GameObject/Replace with prefab")] | |
static void Init() | |
{ | |
// Get existing open window or if none, make a new one: | |
ReplaceWithPrefabWindow window = (ReplaceWithPrefabWindow)EditorWindow.GetWindow(typeof(ReplaceWithPrefabWindow)); | |
window.titleContent = new GUIContent("Replace with prefab"); | |
window.Show(); | |
} | |
void OnGUI() | |
{ | |
GUILayout.Label("Replacement prefab", EditorStyles.boldLabel); | |
prefab = (Transform)EditorGUILayout.ObjectField(prefab, typeof(Transform), false); | |
if (prefab != null && GUILayout.Button("Replace Selection")) | |
{ | |
int group = Undo.GetCurrentGroup(); | |
Undo.SetCurrentGroupName("Undo replace objects with prefab"); | |
foreach (var selectedObject in Selection.gameObjects) | |
{ | |
Transform replacement = (Transform)PrefabUtility.InstantiatePrefab(prefab); | |
Undo.RegisterCreatedObjectUndo(replacement.gameObject, "replacement prefab"); | |
Undo.SetTransformParent(replacement, selectedObject.transform.parent, "set parent"); | |
replacement.name = selectedObject.name; | |
replacement.position = selectedObject.transform.position; | |
replacement.rotation = selectedObject.transform.rotation; | |
replacement.localScale = selectedObject.transform.localScale; | |
int siblingNumber = selectedObject.transform.GetSiblingIndex(); | |
Undo.DestroyObjectImmediate(selectedObject); | |
replacement.SetSiblingIndex(siblingNumber); | |
} | |
Undo.CollapseUndoOperations(group); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment