UNT0031 Asset operations in LoadAttribute method
September 7, 2022 ยท View on GitHub
Asset operations such as asset loading should be avoided in methods decorated with InitializeOnLoadMethod / DidReloadScripts or static constructors in types decorated with InitializeOnLoad. Those methods are called before asset importing is completed and therefore the asset loading can fail resulting in a null object.
Examples of patterns that are flagged by this analyzer
using UnityEditor;
class Loader
{
[InitializeOnLoadMethod]
public void Foo() {
object[] assets = AssetDatabase.LoadAllAssetsAtPath(""foo"");
}
}
Solution
To do initialization after a domain reload which requires asset operations use the AssetPostprocessor.OnPostProcessAllAssets callback. This callback supports all asset operations and has a parameter signaling if there was a domain reload.