Hi all,
I’ve been trying to create a Singleton GameState manager but keep running into the same problem.
I’m using a public delegate to handle events that are changing the GameState enums. I am running into an issue where if I inherit from MonoBehaviour DontDestroyOnLoad is nonfunctional due to my use of the “new” keyword, and if I don’t inherit, I can’t convert my script into an object.
Edit: This still isn’t working. I’m getting an instance of the class as GameStateManager, but my delegate is never being called, even though it should be called on Awake() in the Intro script. Any ideas?
My manager:
using UnityEngine;
using UnityEngine.Events;
using System.Collections;
public enum GameState {
INTRO,
SEARCHING_MATCH,
PLAYER_ONE_TURN,
PLAYER_TWO_TURN,
PLAYER_ONE_WIN,
PLAYER_TWO_WIN,
TIE_GAME
}
public delegate void OnStateChangeHandler();
public class GameStateManager : MonoBehaviour {
protected GameStateManager(){}
public static GameStateManager instance = null;
public event OnStateChangeHandler OnStateChange;
public GameState gameState { get; private set; }
public void Awake()
{
if (instance == null)
{
instance = this;
DontDestroyOnLoad(gameObject);
}
else if (instance != this)
{
DestroyImmediate(gameObject);
}
}
public void setGameState (GameState state)
{
this.gameState = state;
OnStateChange ();
}
public void OnApplicationQuit()
{
instance = null;
}
}
Intro class:
using UnityEngine;
using UnityEngine.Events;
using System.Collections;
public class Intro : MonoBehaviour {
GameStateManager GM;
void Awake() {
GM = GameStateManager.instance;
GM.OnStateChange += HandleOnStateChange;
Debug.Log ("Current game state when Starts: " + GM.gameState);
}
void Start () {
Debug.Log ("Current game state when Starts: " + GM.gameState);
}
public void HandleOnStateChange ()
{
GM.setGameState (GameState.SEARCHING_MATCH);
Debug.Log ("Handling state changes to: " + GM.gameState);
Invoke ("LoadLevel", 3f);
}
public void LoadLevel() {
Application.LoadLevel (1);
}
}