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. Dismiss Notice

Question AssetDatabase.LoadAssetAtPath with valid path still returning null

Discussion in 'Editor & General Support' started by MagmaNevermore, Oct 9, 2023.

  1. MagmaNevermore

    MagmaNevermore

    Joined:
    Mar 16, 2016
    Posts:
    3
    Hi All,

    I have the following code to load an asset:

    Code (CSharp):
    1. string[] _assetGUIDs = AssetDatabase.FindAssets("myAsset", new[] {"Assets/Editor/Data/Settings/" });
    2. string _path = AssetDatabase.GUIDToAssetPath(_assetGUIDs[0]);
    3. ScriptableObject _data = AssetDatabase.LoadAssetAtPath<ScriptableObject>(_path);
    While the AssetDatabase.FindAssets query does return a assetGUID and the GUIDToAssetPath does return a path to a valid .asset file, the AssetDatabase.LoadAssetAtPath returns null.
    This code used to work but after some reorganizing of folders in Unity (and ofcourse changing the path for the FindAssets method accordingly) the LoadAssetAtPath stopped returning a ScriptableObject.

    Anyone an idea where to look for a solution? Project settings, Assembly references?

    Thanks!
     
  2. CodeSmile

    CodeSmile

    Joined:
    Apr 10, 2014
    Posts:
    4,028
    It matters what method you make these calls in. Some event methods such as InitializeOnLoad or static ctors cannot use certain methods because the AssetDatabase has not been fully initialized, thus returning null when you make these calls.
     
    MagmaNevermore likes this.
  3. MagmaNevermore

    MagmaNevermore

    Joined:
    Mar 16, 2016
    Posts:
    3
    Thank you for the reply. I found out what the issue was. While reorganizing the scriptable objects I tried to instantiate lost the reference to their script and therefore they couldn't be loaded. The LoadAssetAtPath will then silently fail.