Hello people,
I am writing here because i did not found anything helpful for my question.
I am working with GameManager, its static Instance and its usage while changing scenes.
I have this scenario: 3 scenes ("GameMenu", "SPGame", "MPGame") and each one has a GameManager instance. Then I have wrote this code:
1) **First Unity Methods**:
private void Awake()
{
PrintExecutionLocation(this);
SetUpGameManager();
}
private void OnEnable()
{
PrintExecutionLocation(this);
SceneManager.sceneLoaded += OnSceneLoaded;
}
**OnSceneLoaded()**:
private void OnSceneLoaded(Scene scene, LoadSceneMode mode)
{
PrintExecutionLocation(this);
Debug.Log(scene.name + " loaded with " + mode.ToString() + " mode");
Debug.Log("Looking for necessary parameters for the current scene...");
GetSceneComponents(scene.name);
}
2) **Custom Methods**
**SetupGameManager()**:
private void SetUpGameManager()
{
PrintExecutionLocation(this);
if (CheckInstance() is true)
{
CheckMode();
}
GetSceneComponents(SceneManager.GetActiveScene().name);
}
**CheckInstance()**:
private bool CheckInstance()
{
PrintExecutionLocation(this);
// if there is another istance of GameManager
if (instance != null && instance != this)
{
Debug.LogWarning("There is already a GameManager instance, i destroy myself (ID: " + GetHashCode() +").");
// destroy it
Destroy(gameObject);
return false;
}
else
{
Debug.LogWarning("There is not a GameManager, i will not destroy myself when loading new scenes (ID: " + GetHashCode() + ").");
instance = this;
// don't destroy the game manager (mainly to keep the score) while changing the levels (aka scenes)
DontDestroyOnLoad(gameObject);
return true;
}
}
**CheckMode()**:
private void CheckMode()
{
PrintExecutionLocation(this);
//If i'm not in main menu scene, activate development mode
Debug.Log("Defining the current scene.");
switch (SceneManager.GetActiveScene().buildIndex)
{
case 0:
//Debug.Log("Sto cominciando dal menù principale.");
_developerMode = false;
Debug.Log("Developer Mode: OFF");
break;
case 1:
//Debug.Log("Sto cominciando dal Single player.");
_developerMode = true;
Debug.Log("Developer Mode: ON");
isSPG = true;
break;
case 2:
//Debug.Log("Sto cominciando dal Multiplayer.");
_developerMode = true;
Debug.Log("Developer Mode: ON");
isSPG = false;
break;
default:
Debug.LogError(SceneManager.GetActiveScene().buildIndex.ToString() + " is not recognized as Scene Index.");
break;
}
}
**GetSceneComponents()**:
private void GetSceneComponents(string index)
{
PrintExecutionLocation(this);
switch (index)
{
case "GameMenu":
Debug.Log("Looking for Canvas references of main menu, settings menu, highscores menu...");
mainMenu = GameObject.Find("MainMenuCanvas").GetComponent
↧