- Home /
How to keep reference linked when replace prefab through editor scripts?
Hi,
Currently I'm woking on some editor code where I have .asset contain all the link to my prefab and these prefab can be modify/replace through another editor script.
Let's say I have a set of prefab : PrefabA, PrefabB, PrefabC
All of these prefab were referenced by ScriptableObject asset
public class AssetData : ScriptableObject
{
public List<GameObject> prefabList;
}
and I have another Editor script to "Replace" these prefab.
GameObject replaceGameObject = new GameObject("TEMP");
Object prefab = AssetDatabase.LoadAssetAtPath(prefabPath, typeof(GameObject));
if(prefab == null)
{
prefab = PrefabUtility.CreateEmptyPrefab(prefabPath);
}
PrefabUtility.ReplacePrefab(replaceGameObject, prefab);
GameObject.DestroyImmediate(replaceGameObject);
The problem is after I finished replace the prefab, The reference in AssetData.asset (also happen to normal scene object serialization as well) above become a missing reference.
Did anyone ever experience this kind of situation?
Thank you,
It seems like your trying to reference prefabs that no longer exist because they were destroyed. Have you tried adding your new prefabs to the list in AssetData? I might be wrong but that's what it looks like to me.
Right, Reference was being destroy but by being replace with another same name(same instanceID, same UDID too I think) prefab kinda strange since it appear that you can keep this reference alive when you did it by hand.
For ex. if you have AssetData link to PrefabA . and you drag a another gameobject from the scene to replace that PrefabA. A reference in AssetData still alive.
Of course I can try to re-reference it again if I have only 1 AssetData but since you may also have another scene/prefab/assetdata reference to these prefab anywhere anytime without being tracked by the editor code, this may not be a right choice for me.
and what I did destroy in the code was a temporary game object in the scene after I finish with the prefab replacement. So the prefab is still there.
Have you tried the different ReplacePrefabOptions
that can be passed in to ReplacePrefab
? For something similar that I did, ReplacePrefabOptions.ConnectToPrefab
was the magic one, along with calling AssetDatabase.SaveAssets(); AssetDatabase.Refresh();
Answer by NathanJSmith · Dec 03, 2018 at 03:55 AM
I see the option: ReplacePrefabOptions.ReplaceNameBased keep reference linked when replace prefab through editor scripts
The script should be
PrefabUtility.ReplacePrefab(source, dest, ReplacePrefabOptions.ReplaceNameBased);