I have written a type of data importer which is designed to grab values from XML files and load them onto prefabs. The general idea is
- Load a ‘base’ prefab (the model which has been imported previously with a script or two attached)
- Grab a bunch of data from the XML and add Components and set their values correctly
- Replace the existing prefab in the asset library with the version that has just been created
The basic script components look like:
// Load the Base prefab
var basePrefab = AssetDatabase.LoadAssetAtPath("Assets/Resources/basePrefabs/" +
node.SelectSingleNode("BasePrefab").InnerText +".prefab",Transform);
// -----------------------
// Add many things in here
// -----------------------
// look for a prefab of similar name
if (AssetDatabase.LoadAssetAtPath("Assets/GamePrefabs/Ships/"+curShip.scriptName +".prefab" , GameObject))
{
// if we found it, just replace
var fab = AssetDatabase.LoadAssetAtPath("Assets/GamePrefabs/Ships/"+curShip.scriptName +".prefab" , GameObject);
curShip.prefabObj = EditorUtility.ReplacePrefab(obj.gameObject,fab,ReplacePrefabOptions.ConnectToPrefab);
} else {
// else create a new prefab
fab = PrefabUtility.CreateEmptyPrefab("Assets/GamePrefabs/Ships/"+curShip.scriptName +".prefab");
curShip.prefabObj = EditorUtility.ReplacePrefab(obj.gameObject,fab,ReplacePrefabOptions.ConnectToPrefab);
}
This works pretty well! However there is a problem. When the script runs, it replaces the prefabs and resets all the instances completely. So for example if I have instantiated a spaceship in the scene and tweaked some of its values (even just moved it off the origin) and added a component or two, it gets completely reset. Back to the origin, all modified data reset, all added components gone.
So is there any way I can replace a prefab without nuking the data? It seems like if I do it manually (get my base prefab, type in all the values, hit Apply) that it doesn’t reset all instances. It’s rather vexing!
To be fair, the documentation doesn't read particularly well. For example, what does "uploading the prefab" mean? Upload to where? What does one option do that the others don't?
– duke_1