Last active
March 3, 2025 16:57
-
-
Save omundy/9044ca673858f39e09af18648bed6590 to your computer and use it in GitHub Desktop.
A game manager (Singleton). Add it to a game object, and child objects for references.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections; | |
using System.Collections.Generic; | |
using UnityEngine; | |
using UnityEngine.Events; | |
/// <summary> | |
/// A game manager using Singleton and Service Locator patterns | |
/// 1. Add this to a game object to make a singleton | |
/// 2. Add child objects with managers (e.g. SoundManager) for global referencing | |
/// </summary> | |
public class GameManager : MonoBehaviour | |
{ | |
///////////////////////////////////////////////////// | |
//////////////////// SINGLETON ////////////////////// | |
///////////////////////////////////////////////////// | |
// *** SINGLETON => make instance accessible outside of class | |
public static GameManager Instance { get; private set; } | |
// *** SINGLETON => only create once | |
public bool singletonCreated = false; | |
public DataManager DataManager { get; set; } | |
public SoundManager SoundManager { get; set; } | |
[Tooltip("Turn on debugging")] | |
public bool DEBUG = true; | |
void CreateSingleton() | |
{ | |
// *** SINGLETON => If instance exists ... | |
if (Instance != null && Instance.singletonCreated) | |
{ | |
while (transform.childCount > 0) | |
{ | |
DestroyImmediate(transform.GetChild(0).gameObject); | |
} | |
// *** SINGLETON => Then delete the object and exit | |
DestroyImmediate(this.gameObject); | |
return; | |
} | |
if (Instance != null && Instance != this) | |
{ | |
Destroy(this); | |
return; | |
} | |
// *** SINGLETON => Only reach this point on the first load... | |
singletonCreated = true; | |
Instance = this; | |
DontDestroyOnLoad(this.gameObject); | |
// @@@ SERVICE LOCATOR => Store references for global access | |
DataManager = GetComponentInChildren<DataManager>(); | |
SoundManager = GetComponentInChildren<SoundManager>(); | |
if (DEBUG) | |
Debug.Log($"*** GameManager (Singleton) created ***"); | |
} | |
private void Awake() | |
{ | |
CreateSingleton(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment