VContainer icon indicating copy to clipboard operation
VContainer copied to clipboard

Can't load VContainerSettings in 1.15.2...?

Open hekk-naoya-kishimoto opened this issue 2 years ago • 2 comments

When loading VContainerSettings in Preloaded Assets in UnityEditor, Application.isPlaying is false and OnEnable() is not working. I think that is why VContainerSettings.Instance is still null in 1.15.2...

https://github.com/hadashiA/VContainer/pull/650

I prepared the following ScriptableObject to check the behavior of Preloaded Assets.

using Cysharp.Threading.Tasks.Linq;
using UnityEditor;
using UnityEngine;
using VContainer.Unity;

public sealed class TestScriptableObject : ScriptableObject
{
    [InitializeOnLoadMethod]
    private static void Initialize()
    {
        EditorApplication.playModeStateChanged += (x) => Debug.Log($"PlayModeStateChanged: {x} (Application.isPlaying: {Application.isPlaying})");
    }

    private void OnEnable()
    {
        Debug.Log($"TestScriptableObject: OnEnable (Application.isPlaying: {Application.isPlaying})");

        UniTaskAsyncEnumerable.EveryUpdate().Subscribe(_ => Debug.Log($"Update (VContainerSettings.Instance: {VContainerSettings.Instance != null}, Application.isPlaying: {Application.isPlaying})"));
    }

    private void OnDisable()
    {
        Debug.Log($"TestScriptableObject: OnDisable (Application.isPlaying: {Application.isPlaying})");
    }
}

20240328

When loading VContainerSettings in Preloaded Assets, Application.isPlaying is difficult to determine.

I checked and it seems that OnDisable() => OnEnable() are executed in this order at the timing when the UnityEditor playback button is pressed. https://docs.unity3d.com/ja/2020.3/ScriptReference/ScriptableObject.OnDisable.html

How about the following modifications...?

public sealed class VContainerSettings : ScriptableObject
{
    void OnEnable()
    {
        // if (Application.isPlaying)
        if (Instance == null)
        {
            Instance = this;

            var activeScene = SceneManager.GetActiveScene();
            if (activeScene.isLoaded)
            {
                OnFirstSceneLoaded(activeScene, default);
            }
            else
            {
                SceneManager.sceneLoaded -= OnFirstSceneLoaded;
                SceneManager.sceneLoaded += OnFirstSceneLoaded;
            }
        }
    }
    
    void OnDisable()
    {
        Instance = null;
    }
}

hekk-naoya-kishimoto avatar Mar 28 '24 03:03 hekk-naoya-kishimoto

Thanks for the verification! I will take it as a reference.

I'm working #654. (Comments welcome)

hadashiA avatar Mar 29 '24 00:03 hadashiA

You saved me a horrible headache! I switched from Zenject to VContainer, I was persuaded by the partial support in ECS and I've been thinking for 1.5h with the problem why it doesn't create RootLifetimeScope - now it's all clear! Thanks!

PrarR avatar Mar 30 '24 16:03 PrarR