Search Unity

  1. Unity 2020.2 has been released.
    Dismiss Notice
  2. Good news ✨ We have more Unite Now videos available for you to watch on-demand! Come check them out and ask our experts any questions!
    Dismiss Notice

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

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

  1. Xarbrough


    Dec 11, 2014
    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. }
    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).