I’ve attached a PRO editor script which should be placed in an empty project.
http://tagenigma.com/qa/Unity3d/DuplicatePrefabWithCloneComponents.unitypackage.zip
Okay I tried to attach but the Unity forums said the file was empty. So I uploaded to my web server.
The package adds an Editor menu item Assets->Duplicate Prefab With Clone Components that you clones PineTree1. The idea is that NewPineTree1 should be a copy of the PineTree1 prefab.
However, there appears to be some Editor UI bugs here.
I have a several issues that I am running into.
-
For some reason cloning the components produces 8 gameObjects. Selection of 1 of these 8 game objects selects all of the game objects. That doesn’t seem right.
-
The NewPineTree1.prefab is missing the components that were cloned and added.
-
The NewPineTree1 prefab shows as a Data Template. What’s that?
4)AddObjectToAsset does not seem capable of adding a cloned component to a prefab. AssetDatabase.AddObjectToAsset(newPrefab, clonedComponent);
Here is a video that does an overview of the package and code that attempts to explain the issues that I see.
http://screencast.com/t/dpw3XYf6
According to the docs, a prefab isn’t considered an asset file.
As a workaround I went back to using ReplacePrefabs and I think the SetDirty and SaveAsset methods helped flush the changes properly.
using UnityEngine;
using UnityEditor;
class DuplicatePrefabWithReplacePrefab : ScriptableWizard
{
[MenuItem("Assets/Duplicate Prefab With Replace Prefab")]
static void CreateWizard()
{
ScriptableWizard.DisplayWizard("Duplicate Prefab With Replace Prefab", typeof(DuplicatePrefabWithReplacePrefab),
"Copy The Prefab");
}
void OnWizardOtherButton()
{
isValid = true;
}
void OnWizardUpdate()
{
}
void Update()
{
}
// called when the "Copy The Prefab" button is pressed
void OnWizardCreate()
{
Debug.Log("Looking for existing prefab...");
UnityEngine.Object existingPrefabObject = EditorUtility.FindAsset("PineTree1.prefab", typeof(Object));
if (null == existingPrefabObject)
{
Debug.Log("Existing prefab object is null");
return;
}
Debug.Log("Creating new prefab...");
string newPrefabName = "Assets/NewPineTree1.prefab";
UnityEngine.Object newPrefab = UnityEditor.EditorUtility.CreateEmptyPrefab(newPrefabName);
if (newPrefab == null)
{
Debug.Log("New prefab is null");
return;
}
Debug.Log("Replacing prefabs with components from existing prefab and copying to new prefab...");
EditorUtility.ReplacePrefab((GameObject)existingPrefabObject, newPrefab, ReplacePrefabOptions.Default);
Debug.Log("Set Dirty on New Prefab");
EditorUtility.SetDirty(newPrefab);
Debug.Log("Saving asset database changes");
AssetDatabase.SaveAssets();
Debug.Log("Saving editor application changes");
EditorApplication.SaveAssets();
Debug.Log("Prefab created successfully");
}
}