Hello folks, I am a bit new and hardly confused with the implementation of a Game Manager. After a bit research i end up with some code that i can’t get it working as it is supposed to be.
The game manager
using UnityEngine;
public enum GameState { NullState, Intro, MainMenu, Game }
public delegate void OnStateChangeHandler();
public class GameManager : MonoBehaviour{
public GameState gameState { get; private set; }
public event OnStateChangeHandler OnStateChange;
static GameManager _instance;
static public bool isActive {
get {
return _instance != null;
}
}
static public GameManager instance
{
get
{
if (_instance == null)
{
_instance = Object.FindObjectOfType(typeof(GameManager)) as GameManager;
if (_instance == null)
{
GameObject go = new GameObject("_gamemanager");
_instance = go.AddComponent<GameManager>();
DontDestroyOnLoad(go);
}
}
return _instance;
}
}
public void SetGameState(GameState gameState) {
this.gameState = gameState;
if(OnStateChange!=null) {
OnStateChange();
}
}
}
I suppose this its quite OK; then I first create a NEW scene Blank… then i created a empty game object in it and called it START. , then i created a START script on it. that shows like this :
sing UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class START : MonoBehaviour {
GameManager GM;
void Awake () {
GM = GameManager.instance;
GM.OnStateChange += HandleOnStateChange;
Debug.Log("Current game state when Awakes: " + GM.gameState);
GM.SetGameState(GameState.Intro);
}
void Start () {
Debug.Log("Current game state when Starts: " + GM.gameState);
}
public void HandleOnStateChange ()
{
Debug.Log("Handling state change to: " + GM.gameState);
Invoke ("charge", 3f);
}
public void charge(){
Application.LoadLevel("STAGECLEAR");
}
}
Things seems to work fine until here… but when i Load STAGECLEAR SCENE… if i use same trick it throws me an error :
MissingReferenceException: The object of type ‘START’ has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
The fact is the start scene should be destroyed… and i see _gamemanager is still alive… on the new scene the point seems to broke up when i add this line on the STAGECLEAR code ( which i try to use the same thing to update de gamestate);
STAGECLEAR CODE ( its very huge so i post the awake and start function );
void Awake(){
GM = GameManager.instance;
GM.OnStateChange += HandleOnStateChange;
}
public void HandleOnStateChange ()
{
Debug.Log("estoyenjuego!");
}
void Start () {
GM.SetGameState (GameState.MainMenu);
}
If i remove the line GM.SetGameState(GameState.MainMenu); from STAGECLEAR Scene… it loads the scene but the thing is that i am not able to change the gamestate inside this scene and thats the purpose of the game manager though…
Arghhhhh
Hope the info is enough and thx you guys all, because im learning from 0… and you are the teacher !