using System.Collections; using System.Threading.Tasks; using UnityEngine; using UnityEngine.SceneManagement; /// /// manages the logic of loading /// public class LoadingManager : MonoBehaviour { public const string LevelToLoad = nameof(LevelToLoad); public const string SceneToLoad = nameof(SceneToLoad); public const int NoLevel = -1; private LoadingScreen loadingScreen; void Start() { loadingScreen = GetComponent(); loadingScreen.ScreenActivated += LoadTargetSceneAndCloseOthers; loadingScreen.ShowLoadingScreen(); } /// /// loads the target scene after given time /// private void LoadTargetSceneAndCloseOthers() { StartCoroutine(LoadSceneAfterTime()); IEnumerator LoadSceneAfterTime() { yield return new WaitForSeconds(GlobalConfig.Instance.Current.loadingAddedTime); loadingScreen.ScreenActivated -= LoadTargetSceneAndCloseOthers; SceneManager.sceneLoaded += StartHidingLoadingScreen; var sceneToLoad = PlayerPrefs.GetString(SceneToLoad); //unload all scenes except loading screen for (int i = 0; i < SceneManager.sceneCount; i++) { var scene = SceneManager.GetSceneAt(i); if (scene.name == gameObject.scene.name) continue; SceneManager.UnloadSceneAsync(scene.name); } SceneManager.LoadScene(sceneToLoad, LoadSceneMode.Additive); } } /// /// hide loading screen after target scene has finished loading /// /// unused /// unused private void StartHidingLoadingScreen(Scene arg0, LoadSceneMode arg1) { SceneManager.sceneLoaded -= StartHidingLoadingScreen; loadingScreen.ScreenDeactivated += StartLoadingLevel; loadingScreen.HideLoadingScreen(); } /// /// when loading screen is hidden, we load the level if we have a level to load (might not, if we have loaded another scene than the Game scene) /// private async void StartLoadingLevel() { loadingScreen.ScreenDeactivated -= StartLoadingLevel; LevelManager.Instance.LevelLoaded += UnloadLoadingScreenScene; var levelToLoad = PlayerPrefs.GetInt(LevelToLoad, NoLevel); if (levelToLoad == NoLevel) { UnloadLoadingScreenScene(null); } else { string lvlName = $"Level{levelToLoad}"; await LevelManager.Instance.LoadLevel(lvlName, true, LevelManagerScript.PlacementAnimation); } } /// /// close the loading screen scene and start playing! w00t w00t /// /// private void UnloadLoadingScreenScene(GatherAndDefend.LevelEditor.Level level) { LevelManager.Instance.LevelLoaded -= UnloadLoadingScreenScene; SceneManager.UnloadSceneAsync(gameObject.scene.name); } }