Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Utility for batch objects replace for Unity
using UnityEngine;
using UnityEditor;
namespace Alt3d
{
public class BatchObjectsReplaceWindow : EditorWindow
{
private GameObject Prefab;
private bool ReplaceNames = true;
private void OnGUI()
{
EditorGUILayout.Space();
EditorGUILayout.Space();
Prefab = (GameObject) EditorGUILayout.ObjectField("Target prefab", Prefab, typeof(GameObject),false);
ReplaceNames = EditorGUILayout.Toggle("Replace names", ReplaceNames);
EditorGUILayout.Space();
if (GUILayout.Button("Replace Selection"))
{
var selection = Selection.gameObjects;
var replaceObjects = ReplaceObjects(selection, Prefab, ReplaceNames);
DestroyObjects(selection);
Selection.objects = replaceObjects;
}
}
private static Object[] ReplaceObjects(GameObject[] array, GameObject prefab, bool replaceNames)
{
if (!prefab)
{
return new Object[0];
}
var result = new Object[array.Length];
for (int i = 0; i < array.Length; i++)
{
var sourceGameObject = array[i];
if (!sourceGameObject)
{
result[i] = null;
continue;
}
var resultGameObject = (GameObject) PrefabUtility.InstantiatePrefab(prefab);
if (replaceNames)
{
resultGameObject.name = prefab.name;
}
else
{
resultGameObject.name = sourceGameObject.name;
}
var sourceTransform = sourceGameObject.transform;
var resultTransform = resultGameObject.transform;
resultTransform.parent = sourceTransform.parent;
resultTransform.position = sourceTransform.position;
resultTransform.rotation = sourceTransform.rotation;
resultTransform.localScale = sourceTransform.localScale;
result[i] = resultGameObject;
}
return result;
}
private static void DestroyObjects(GameObject[] array)
{
for (int i = 0; i < array.Length; i++)
{
if (array[i])
{
DestroyImmediate(array[i]);
}
}
}
[MenuItem("Develop/Batch Objects Replace")]
private static void OpenWindow()
{
GetWindow<BatchObjectsReplaceWindow>( "Batch Objects Replace");
}
}
}
@alt3d

This comment has been minimized.

Copy link
Owner Author

alt3d commented Oct 7, 2019

Снимок экрана (133)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.