diff --git a/VContainer/Assets/VContainer/Runtime/Unity/VContainerSettings.cs b/VContainer/Assets/VContainer/Runtime/Unity/VContainerSettings.cs index 71bcf085..42ca3481 100644 --- a/VContainer/Assets/VContainer/Runtime/Unity/VContainerSettings.cs +++ b/VContainer/Assets/VContainer/Runtime/Unity/VContainerSettings.cs @@ -48,6 +48,23 @@ public static void CreateAsset() preloadedAssets.Add(newSettings); UnityEditor.PlayerSettings.SetPreloadedAssets(preloadedAssets.ToArray()); } + + public static void LoadInstanceFromPreloadAssets() + { + var preloadAsset = UnityEditor.PlayerSettings.GetPreloadedAssets().FirstOrDefault(x => x is VContainerSettings); + if (preloadAsset is VContainerSettings instance) + { + instance.OnDisable(); + instance.OnEnable(); + } + } + + [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)] + static void RuntimeInitialize() + { + // For editor, we need to load the Preload asset manually. + LoadInstanceFromPreloadAssets(); + } #endif public LifetimeScope GetOrCreateRootLifetimeScopeInstance() @@ -88,13 +105,18 @@ void OnEnable() } } + void OnDisable() + { + Instance = null; + } + void OnFirstSceneLoaded(Scene scene, LoadSceneMode mode) { if (RootLifetimeScope != null && RootLifetimeScope.autoRun && (rootLifetimeScopeInstance == null || rootLifetimeScopeInstance.Container == null)) { - GetOrCreateRootLifetimeScopeInstance().Build(); + GetOrCreateRootLifetimeScopeInstance(); } SceneManager.sceneLoaded -= OnFirstSceneLoaded; }