Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

LoadAssetAtPath returns null after compiling.

Discussion in 'Editor & General Support' started by geniusz, Dec 20, 2021.

  1. geniusz

    geniusz

    Joined:
    Nov 21, 2014
    Posts:
    38
    My problem is LoadAssetAtPath will return null in EditorWindow.OnEnable after compiling if AssetDatabase.SaveAssetIfDirty gets called in OnDisable.

    Actually I'm not sure if it is a bug or not, I'm working with 2020.3.24, here is an example:

    Code (CSharp):
    1. [CreateAssetMenu(fileName = "BuildConfig.asset", menuName = "Build Config")]
    2. public class BuildConfig : ScriptableObject
    3. {
    4.     const string CONFIG_PATH = "Assets/Editor/BuildConfig.asset";
    5.  
    6.     public class Window : EditorWindow
    7.     {
    8.         BuildConfig _config
    9.    
    10.         [MenuItem("Window/Build Config")]
    11.         private static void OpenWindow()
    12.         {
    13.             GetWindow<Window>(true, "Build Config");
    14.         }
    15.  
    16.         private void OnEnable()
    17.         {
    18.             _config = AssetDatabase.LoadAssetAtPath<BuildConfig>(CONFIG_PATH);
    19.             Debug.Log($"config is null: {_config is null}");
    20.         }
    21.        
    22.         private void OnDisable()
    23.         {
    24.             EditorUtility.SetDirty(_config);
    25.             AssetDatabase.SaveAssetIfDirty(_config);
    26.         }
    27.     }
    28. }
    Steps to reproduce:
    1. Create an asset at CONFIG_PATH with the menu
    2. Open the window, you will see "config is null: False" in the console.
    3. Make some changes to the script, let the code recompile, after that you will see "config is null: True".
    I've also tried LoadMainAssetAtPath or LoadAssetAtPath(CONFIG_PATH, typeof(Object)), and I got same result.

    But it's weired the following code will work:

    Code (CSharp):
    1. var all = AssetDatabase.LoadAllAssetsAtPath(CONFIG_PATH);
    2. _config = all[0] as BuildConfig;
     
    caogtaa likes this.
  2. caogtaa

    caogtaa

    Joined:
    Apr 27, 2016
    Posts:
    13
    I have the exactly same problem.
    LoadAssetAtPath() not always work in EditorWindow.OnEnable(), it always fail after Unity recompiling some code.
    I'm using Unity 2021.3.6f.
     
    ununion likes this.
  3. ununion

    ununion

    Joined:
    Dec 2, 2018
    Posts:
    272
    do you find the solution?
     
    caogtaa likes this.
  4. caogtaa

    caogtaa

    Joined:
    Apr 27, 2016
    Posts:
    13
    Use `AssetDatabase.LoadAllAssetsAtPath();` instead, which is mentioned by geniusz.