Hi everyone,
I’m new to Unity so I have a lot to learn…
I’m trying to set up a game manager for my game, I have been following this tutorial and understood most of it: Creating a simple GameManager using Unity3D | Packt Hub
Now, as per the tutorial, I have a game manager script that is a Singleton, and I have a scene called Intro, that has an empty gameobject with an Intro.cs script.
The issue I have is that when I run the game, the Intro script executes Awake and Start, but the ChangeState function is not either called, or passed to the delegate (not sure about the correct wording).
I cannot really tell where the problem is, and I hope you guys can help me understanding it.
GameManager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//list of game states
public enum GameState { INTRO, MAIN_MENU }
//callback to change the gameState
public delegate void OnStateChangeHandler();
public class GameManager
{
protected GameManager() {}
static GameManager instance = null; //global variable where the gm instance is stored
public event OnStateChangeHandler OnStateChange; //event to change state
public GameState gameState { get; private set; } //getter for the current game state
//getter for the gm instance
public static GameManager Instance{
get {
if (GameManager.instance == null) { //if there is no instance, create one
GameManager.instance = new GameManager();
}
return GameManager.instance; //returns the instance
}
}
//function to change the state
public void SetGameState(GameState state) {
this.gameState = state;
OnStateChange();
}
public void OnApplicationQuit() {
GameManager.instance = null;
}
}
Intro.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class Intro : MonoBehaviour
{
GameManager gm;
void Awake() {
gm = GameManager.Instance;
gm.OnStateChange += ChangeState;
Debug.Log("Awake - current state: " + gm.gameState);
}
void Start() {
Debug.Log("Start - current state: " + gm.gameState);
}
public void ChangeState() {
gm.SetGameState(GameState.MAIN_MENU);
Debug.Log("About to change state to: " + gm.gameState);
Invoke("LoadLevel", 2f);
}
public void LoadLevel() {
SceneManager.LoadScene(1);
}
}
Thanks for your support!