Create prefab from model in AssetPostprocessor without losing mesh connections?
I'm trying to create a prefab from a model in OnPostprocessModel. The prefab gets created and the model hierarchy is added but the Meshes in the Meshfilters are all set to None. Can anyone explain this behaviour?
What I do is basically this:
public void OnPostprocessModel(GameObject go) {
PrefabUtility.CreatePrefab("Assets/test.prefab", go);
}
,
Answer by dan_at_sop · Nov 26, 2015 at 02:09 PM
I had this same problem just today - surprisingly close to you!
I figured you have the save the prefab's meshes again. This fixed it for me:
MeshFilter[] mfs = toPrefab.GetComponentsInChildren<MeshFilter>();
foreach(MeshFilter mf in mfs) {
Debug.Log("Saving mesh: "+mf.name +"_M" );
char[] invalids = System.IO.Path.GetInvalidFileNameChars();
String newName = String.Join("_", mf.name.Split(invalids, StringSplitOptions.RemoveEmptyEntries) ).TrimEnd('.');
AssetDatabase.CreateAsset(mf.mesh, "Assets/TempPrefabs/SavedMesh/" + newName +"_M" + ".asset");
}
PrefabUtility.CreatePrefab("Assets/TempPrefabs/Resources/"+toPrefab.gameObject.name+".prefab",toPrefab.gameObject,ReplacePrefabOptions.ReplaceNameBased);
This fixed the issue for me, I confirmed hours ago that my mesh and texture were being imported correctly, but when I checked my prefab it was just a blank $$anonymous$$esh Renderer and $$anonymous$$esh Filter. Saving the asset allows the prefab to be created as expected.
Answer by AtsumuOno · Jun 14, 2017 at 10:04 AM
https://docs.unity3d.com/ScriptReference/AssetPostprocessor.OnPostprocessModel.html
Any references to game objects or meshes will become invalid after the import has been completed. Thus it is not possible to create a new prefab in a different file from OnPostprocessModel that references meshes in the imported fbx file.
Please try the OnPostprocessAllAssets method.
static void OnPostprocessAllAssets (string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths)
{
foreach (string assetPath in importedAssets)
{
if (assetPath.Contains("Your target asset path") && System.IO.Path.GetExtension(assetPath) == "Your target asset extension")
{
var go = (GameObject)AssetDatabase.LoadAssetAtPath(assetPath, typeof(GameObject));
PrefabUtility.CreatePrefab("Assets/test.prefab", go);
}
}
}
Answer by say_forever · Nov 23, 2015 at 12:16 PM
public Transform prefab;
void Start() {
Instantiate(prefab, new Vector3(0, 0, 0), Quaternion.identity);
}
reference this
Sorry, I was asking how to create the prefab, not how to instantiate it. That it is made through an assetpostprocessor is also important. I made this more clear in the description