Skip to content

Instantly share code, notes, and snippets.

@skjalgsm
Created April 21, 2021 17:49
Show Gist options
  • Save skjalgsm/b097354e854a9a8b471f2c63d6b05c66 to your computer and use it in GitHub Desktop.
Save skjalgsm/b097354e854a9a8b471f2c63d6b05c66 to your computer and use it in GitHub Desktop.
Replaces a gameobject with a prefab
public class ReplaceGameObjectsWizard : ScriptableWizard
{
private const string PrefsPath = "ReplaceGameObjects.PrefabPath";
public GameObject Prefab;
[MenuItem("GameObject/Replace GameObjects",false,0)]
static void CreateWizard ()
{
UnityEngine.Object[] objectsOfTypeAll = Resources.FindObjectsOfTypeAll(typeof(ReplaceGameObjectsWizard));
if (objectsOfTypeAll.Length == 0)
{
var wiz = DisplayWizard<ReplaceGameObjectsWizard>("Replace GameObjects", "Replace");
if (wiz.Prefab == null)
{
wiz.Prefab = AssetDatabase.LoadAssetAtPath<GameObject>(EditorPrefs.GetString(PrefsPath));
}
}
}
public class TransformValue : IComparable<TransformValue>
{
public string Name { get; set; }
public Transform Parent { get; set; }
public int SiblingIndex { get; set; }
public Vector3 Position { get; set; }
public Quaternion Rotation { get; set; }
public Vector3 Scale { get; set; }
public TransformValue(Transform transform)
{
Name = transform.name;
Parent = transform.parent;
SiblingIndex = transform.GetSiblingIndex();
Position = transform.localPosition;
Rotation = transform.localRotation;
Scale = transform.localScale;
}
public void SetValues(Transform transform)
{
transform.name = Name;
transform.SetParent(Parent, false);
transform.SetSiblingIndex(SiblingIndex);
transform.localPosition = Position;
transform.localRotation = Rotation;
transform.localScale = Scale;
}
public int CompareTo(TransformValue other)
{
if (ReferenceEquals(this, other))
{
return 0;
}
if (ReferenceEquals(null, other))
{
return 1;
}
return SiblingIndex.CompareTo(other.SiblingIndex);
}
}
void OnWizardCreate ()
{
EditorPrefs.SetString(PrefsPath, AssetDatabase.GetAssetPath(Prefab));
var replace = Selection.gameObjects;
var transformValues = new TransformValue[replace.Length];
for (var index = 0; index < replace.Length; index++)
{
GameObject go = replace[index];
var t = go.transform;
transformValues[index] = new TransformValue(t);
}
Array.Sort(transformValues);
var newObjs = new GameObject[replace.Length];
Undo.IncrementCurrentGroup();
Undo.SetCurrentGroupName("Replace GameObjects with prefabs");
for (var index = 0; index < transformValues.Length; index++)
{
var value = transformValues[index];
var newObj = PrefabUtility.InstantiatePrefab(Prefab) as GameObject;
value.SetValues(newObj.transform);
Undo.RegisterCreatedObjectUndo(newObj, "created prefab");
newObjs[index] = newObj;
}
for (var index = 0; index < replace.Length; index++)
{
GameObject go = replace[index];
Undo.DestroyObjectImmediate(go);
}
Selection.objects = newObjs;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment