// Convert into hierarchical prefab public static void ReplacePrefabInHierarchyByInstantiator(GameObject a_rGameObjectToConvert) { // Loop through the child transforms // and search the nested prefab Transform a_rGameObjectToConvertTransform = a_rGameObjectToConvert.transform;; // If there already is a instantiator remove it NestedPrefabsInstantiator rNestedPrefabsInstantiator = a_rGameObjectToConvert.GetComponent <NestedPrefabsInstantiator>(); if (rNestedPrefabsInstantiator != null) { rNestedPrefabsInstantiator.Clear(); } // Loop in reverse to allow direct child destruction for (int i = a_rGameObjectToConvertTransform.GetChildCount() - 1; i >= 0; i--) { // Check if Prefab replacement hasn't destroy the parent if (a_rGameObjectToConvertTransform != null) { Transform rChildTransform = a_rGameObjectToConvertTransform.GetChild(i); GameObject rChildGameObject = rChildTransform.gameObject; // If we encounter a nested prefab if (IsNestedPrefab(rChildGameObject, a_rGameObjectToConvert)) { // Removing the child from the scene graph in order to avoid // unwanted prefab reconnection propagation // (A prefab instance nested into an other instance of the same prefab will // reconnect the the top most instance thus destroying the nested prefab too soon (i.e. destroying the current child) // Keep the local Transform in order to keep the override properties NestedPrefabUtility.ChangeParentAndKeepSameLocalTransform(rChildTransform, null); // Force the prefab reconnection to have an up to date property modifications PrefabUtility.ReconnectToLastPrefab(rChildGameObject); // Reconnect to the scene graph NestedPrefabUtility.ChangeParentAndKeepSameLocalTransform(rChildTransform, a_rGameObjectToConvertTransform); // Create the nested prefab instantiator on his parent NestedPrefabsInstantiator rNestedPrefabInstantiator = NestedPrefabComponentUtility.GetOrCreate <NestedPrefabsInstantiator>(a_rGameObjectToConvert); // Add the current nested prefab game object rNestedPrefabInstantiator.Add(rChildGameObject); // Destroy the nested prefab game object Editor.DestroyImmediate(rChildGameObject); } else // If not a prefab go deeper { ReplacePrefabInHierarchyByInstantiator(rChildGameObject); } } } }
// Convert into hierarchical prefab public static HierarchicalPrefabInstance ConvertIntoHierarchicalPrefab(GameObject a_rGameObjectToConvert) { // Add the hierarchical prefab if not there HierarchicalPrefabInstance rHierarchicalPrefabInstance = NestedPrefabComponentUtility.GetOrCreate <HierarchicalPrefabInstance>(a_rGameObjectToConvert); // Clear the hierarchy from the prefab and add instantiator to respawn them when needed TrimHierarchicalPrefab(a_rGameObjectToConvert.transform); return(rHierarchicalPrefabInstance); }