Search Unity

How to get reference to prefab during or right after its import?

Discussion in 'Prefabs' started by Xarbrough, Nov 19, 2020.

  1. Xarbrough

    Xarbrough

    Joined:
    Dec 11, 2014
    Posts:
    1,188
    When a prefab with a special name is created in my project I would like to obtain its asset reference and add it to a ScriptableObject somewhere else. Ideally, this would happen during import, but as far as I see it, there's no way to obtain the "real" GameObject that shows in the project window until the import is over. So during callbacks like OnPostprocessModel or OnPostprocessAllAssets the GameObject will always be null.

    Currently, I'm working around this like so:

    Code (CSharp):
    1. private static void OnPostprocessAllAssets(
    2.     string[] importedAssets,
    3.     string[] deletedAssets,
    4.     string[] movedAssets,
    5.     string[] movedFromAssetPaths)
    6. {
    7.     // If importing my special prefab.
    8.     EditorApplication.delayCall += () => RegisterToLookup(importedAssets[0]);
    9. }
    10.  
    11. private void RegisterToLookup(string path)
    12. {
    13.     var prefabAsset = AssetDatabase.LoadAssetAtPath<GameObject>(path);
    14.     // Store in lookup table and save.
    15. }
    Is the only/correct/recommended way of doing this? Is it even save? I simply assume that the import will be over by the end of this editor frame, but maybe there are reasons why it could take two or three frames?

    Also, another concern: usually when editing many assets it is recommended to do the processing in between calls to
    AssetDatabase.StartAssetEditing()[ICODE] and [ICODE]AssetDatabase.StopAssetEditing()ICODE] to batch all edits and then only reimport at the end. If I now start importing assets, then wait a frame, then edit some other assets, then reimport, I'm worried that I'll break this batching of imports and instead import and wait for each single asset to finish (which is much slower in my experience).