-
Notifications
You must be signed in to change notification settings - Fork 8
/
LevelLogic.cs
112 lines (91 loc) · 2.68 KB
/
LevelLogic.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class LevelLogic : MonoBehaviour
{
[Header("Scene state")]
public int backScene;
public static int currentScene;
public int nextScene;
int managerScene;
int sceneCountInBuildSettings;
[Header("Loader")]
int sceneToLoad;
bool loading = false;
AsyncOperation loadAsync = null;
AsyncOperation unloadAsync = null;
float fadeTime = 1.0f;
[Header("UI")]
[SerializeField]
Image blackScreen;
void Start()
{
blackScreen.color = Color.black;
blackScreen.CrossFadeAlpha(0, fadeTime, true);
if (SceneManager.sceneCount >= 2) SceneManager.SetActiveScene(SceneManager.GetSceneAt(1));
UpdateSceneState();
if (currentScene == managerScene) StartLoad(nextScene);
AudioManager.Initialize();
}
void UpdateSceneState()
{
sceneCountInBuildSettings = SceneManager.sceneCountInBuildSettings;
managerScene = 0;
currentScene = SceneManager.GetActiveScene().buildIndex;
if (currentScene <= managerScene + 1) backScene = sceneCountInBuildSettings - 1;
else backScene = currentScene - 1;
if (currentScene >= sceneCountInBuildSettings - 1) nextScene = 1;
else nextScene = currentScene + 1;
}
public void StartLoad(int index)
{
if (loading) return;
loading = true;
sceneToLoad = index;
FadeOut();
}
void Load()
{
if (sceneToLoad == -1)
{
Application.Quit();
return;
}
if (currentScene != managerScene) unloadAsync = SceneManager.UnloadSceneAsync(currentScene);
loadAsync = SceneManager.LoadSceneAsync(sceneToLoad, LoadSceneMode.Additive);
StartCoroutine(Loading());
}
void FadeIn()
{
blackScreen.CrossFadeAlpha(0, fadeTime, true);
}
void FadeOut()
{
blackScreen.CrossFadeAlpha(1.0f, fadeTime, true);
StartCoroutine(WaitForFade());
}
IEnumerator Loading()
{
while (loading)
{
if ((unloadAsync == null || unloadAsync.isDone) && loadAsync.isDone)
{
unloadAsync = null;
loadAsync = null;
FadeIn();
SceneManager.SetActiveScene(SceneManager.GetSceneByBuildIndex(sceneToLoad));
UpdateSceneState();
loading = false;
}
yield return null;
}
}
IEnumerator WaitForFade()
{
yield return new WaitForSeconds(fadeTime);
Load();
}
}