I have this scene with hundreds of copies of the same asset. How do I substitute them by a prefab? Keeping the same position and rotation is important.
Thx
Ok, two questions to clarify:
- Are any of these assets referenced somewhere else? In other words: would it be OK to automatically delete and recreate (at the same spot) all of these assets or will that cause a multitude of broken links?
- How do you know (automatically) what assets need to be replaced? E.g. do you mean “all assets with a specific name?” Or do they all have a specific tag? Or are they all assets that are childs of a specifc gameObject? Or all gameObjects that have a specifc component? Or maybe “just all assets that I have currently selected?”
I assume the answer to 1 is “broken links don’t matter - recreate is fine” and the answer to 2 is “all objects that I have currently selected”.
Then you could write an editor tool like this:
// put this in some editor scripte, i.e. in some C# file under "Editor/"
// directory with "using UnityEditor;" included
[MenuItem("Helper/Replace Objects With Prefab")]
static void HelperReplaceObjectsWithPrefab()
{
var prefab = AssetDatabase.LoadAssetAtPath<GameObject>("Assets/myPrefab.prefab"); // put the location of the prefab here
// go over all selected objects. Change this if you want to go
// through other objects, e.g. GameObject.FindWithTag ...
foreach (GameObject s in Selection.objects)
{
// create a new prefab
var go = (GameObject)PrefabUtility.InstantiatePrefab(prefab);
go.name = s.name; // remember name
EditorUtility.CopySerialized(s.transform, go.transform); // remember position/rotation etc..
go.transform.parent = s.transform.parent; // put into hierarchy
PrefabUtility.RecordPrefabInstancePropertyModifications(go); // fix modified properties
GameObject.DestroyImmediate(s); // destroy old
}
}
The code is 100% untested and written out of the blue, but I hope you get the idea ^^.