OnPostprocessAllAssets ReplacePrefab breaks in-scene prefabs..?

Hi, I’m using AssetPostProcessor to dynamically generate prefabs on import - all is working well until any of the models are re-imported: any of the previously generated prefabs that are in scene turn red and are marked as ‘missing’, even though they still appear within the project, albeit having been replaced.

How can I modify this code to make sure that the prefabs link remains when the prefabs are regenerated through the model being changed?

Code:

private static void OnPostprocessAllAssets(
	string[] importedAssets,
	string[] deletedAssets,
	string[] movedAssets,
	string[] movedFromAssetPaths) 
{
	foreach (string assetPath in importedAssets){

		if (assetPath.IndexOf("/tile_") != -1 && assetPath.EndsWith(".fbx"))
		{
			GameObject g = Resources.LoadAssetAtPath<GameObject>(assetPath);
			// generate prefab
			Object prefab = PrefabUtility.CreateEmptyPrefab("Assets/prefabs/Terrain/Tiles/PFAB_" + g.name + ".prefab");
			PrefabUtility.ReplacePrefab(g, prefab, ReplacePrefabOptions.ReplaceNameBased);
		}
	}
}

Many thanks,

Jules

As it turns out, I ‘fixed’ this by simplifying the problem, in this particular case there was no reason to rebuild the prefab any time a new model was imported as all I’m currently doing is wrapping the model up into a prefab. So I just checked whether the prefab exists first and only built it if it dosen’t.

private static void OnPostprocessAllAssets(
	string[] importedAssets,
	string[] deletedAssets,
	string[] movedAssets,
	string[] movedFromAssetPaths) 
{

	//Debug.Log (importedAssets);

	foreach (string assetPath in importedAssets){

		// hex ground imports
		//Debug.Log (assetPath);
		if (assetPath.IndexOf("/tile_") != -1 && assetPath.EndsWith(".fbx"))
		{
			// check if we have an existing prefab
			GameObject g = Resources.LoadAssetAtPath<GameObject>(assetPath);
			Object prefab = Resources.LoadAssetAtPath<Object>("Assets/prefabs/Terrain/Tiles/PFAB_" + g.name + ".prefab");
			// generate prefab
			if (!prefab){
				PrefabUtility.CreatePrefab("Assets/prefabs/Terrain/Tiles/PFAB_" + g.name + ".prefab", g);
			}
		}
	}
}

I’d still very much like to understand how to do this properly, since this is not a genuine solution, just a bypassing of the problem.