Skip to content

Instantly share code, notes, and snippets.

@TobiasPott
Created March 4, 2020 10:25
Show Gist options
  • Save TobiasPott/ea92398f3de9b776dc52417c86bfecc3 to your computer and use it in GitHub Desktop.
Save TobiasPott/ea92398f3de9b776dc52417c86bfecc3 to your computer and use it in GitHub Desktop.
/* This wizard will replace a selection with an object or prefab.
* Scene objects will be cloned (destroying their prefab links).
* Original coding by 'yesfish', nabbed from Unity Forums
* 'keep parent' added by Dave A (also removed 'rotation' option, using localRotation
* 2020/03/04 (Tobias Pott): Updated code for use in Unity 2019.x and fixed problems with Undo/Redo insertion
*/
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
public class ReplaceSelection : ScriptableWizard
{
private static GameObject replacement = null;
private static bool keep = false;
public GameObject ReplacementObject = null;
public bool KeepOriginals = false;
[MenuItem("GameObject/Replace Selection...")]
private static void CreateWizard()
{
ScriptableWizard.DisplayWizard(
"Replace Selection", typeof(ReplaceSelection), "Replace");
}
public ReplaceSelection()
{
ReplacementObject = replacement;
KeepOriginals = keep;
}
private void OnWizardUpdate()
{
replacement = ReplacementObject;
keep = KeepOriginals;
}
private void OnWizardCreate()
{
if (replacement == null)
return;
Transform[] transforms = Selection.GetTransforms(
SelectionMode.TopLevel | SelectionMode.OnlyUserModifiable);
string undoName = "Replace Selection";
Undo.RecordObjects(transforms, undoName);
List<GameObject> created = new List<GameObject>();
foreach (Transform t in transforms)
{
GameObject g;
PrefabAssetType pref = PrefabUtility.GetPrefabAssetType(replacement);
if (pref != PrefabAssetType.NotAPrefab)
{
g = (GameObject)PrefabUtility.InstantiatePrefab(replacement);
PrefabUtility.RecordPrefabInstancePropertyModifications(g);
}
else
{
g = (GameObject)Editor.Instantiate(replacement);
}
Transform gTransform = g.transform;
gTransform.parent = t.parent;
g.name = replacement.name;
gTransform.localPosition = t.localPosition;
gTransform.localScale = t.localScale;
gTransform.localRotation = t.localRotation;
Undo.RegisterCreatedObjectUndo(g, undoName);
created.Add(g);
}
//Undo.RecordObjects(created.ToArray(), undoName);
if (!keep)
{
foreach (GameObject g in Selection.gameObjects)
{
Undo.DestroyObjectImmediate(g);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment