In this section, we will implement a Singleton and Game Manager class. We will attempt to utilize some core Unity API features to adapt the pattern for use in the engine:
- For the first step of the process, we will implement the Singleton class. To make it easier to understand its intricacies, we will split it up into two distinct segments:
using UnityEngine;
namespace Chapter.Singleton
{
public class Singleton<T> :
MonoBehaviour where T : Component {
private static T _instance;
public static T Instance
{
get
{
if (_instance == null)
{
_instance = FindObjectOfType<T>();
if (_instance == null)
{
GameObject obj = new GameObject();
obj.name = typeof(T).Name;
_instance = obj.AddComponent<T>();
}
}
...