Search Unity

Question Callback after assembly reloads but before scriptable objects on enable ?

Discussion in 'Scripting' started by JusteTools, May 31, 2023.

  1. JusteTools

    JusteTools

    Joined:
    Mar 19, 2021
    Posts:
    14
    Hi everyone, I'm having an issue regarding execution order of callbacks.

    I would like users to be able to run some code after an assembly reloads but before ScriptableObject.OnEnable is called.

    Problem is that RuntimeInitializeOnLoadMethod, and AssemblyReloadEvents.afterAssemblyReload are called after OnEnable.

    When launching play mode in the editor, the order seems to be:
    - Assembly reloads
    - OnEnable is called with EditorApplication.isPlayingOrWillChangePlaymode set to true
    - RuntimeInitializeOnLoadMethod and AssemblyReloadEvents.afterAssemblyReload are called

    Is there any callback that actually run after the assembly reloads, before the OnEnable methods ?

    Thanks a lot !
     
  2. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,531
    When are you registered the 'afterAssemblyReload' event? That would have to be done sometime after the assembly is loaded and before it is called. Why not there?

    I just tried flagging an editor script 'InitializeOnLoad', and then in the static constructor for that script I both registered for this event as well as just logged a message. Something like:

    Code (csharp):
    1.     [InitializeOnLoad]
    2.     public class TestEditorMenu
    3.     {
    4.  
    5.         static TestEditorMenu()
    6.         {
    7.             AssemblyReloadEvents.afterAssemblyReload += () => { Debug.Log("afterAssemblyReload: " + nameof(TestEditorMenu)); };
    8.             Debug.Log("InitializeOnLoad: " + nameof(TestEditorMenu));
    9.         }
    10. }
    And I also created a scriptable object that logged during OnEnable.

    I got this output:
    upload_2023-5-31_13-42-14.png

    It appears the static constructor on a class flagged InitializeOnLoad fired before the SO fired OnEnable.

    Does this suffice for what you need?
     
  3. JusteTools

    JusteTools

    Joined:
    Mar 19, 2021
    Posts:
    14
    I didn't try the editor version of InitializeOnLoad because I wanted it to work in build too, but it seems to run at the correct time !

    I'm doing this:
    Code (CSharp):
    1. #if UNITY_EDITOR
    2.         [UnityEditor.InitializeOnLoadMethod]
    3. #else
    4.         [RuntimeInitializeOnLoadMethod]
    5. #endif
    Which should work fine in any case, thanks a lot !