I am creating a Manager
class that implements singleton patterns with C# interface.
I came up with a structure to apply a singleton pattern to the Manager
class, inherit it to my children, and extend the functionality. However, if I try to access it from the other class, I can only access the Manager
class.
I think I need to modify the code or structure, what should I do?
ISingleton.cs
using System;
using System.Collections.Generic;
using UnityEngine;
public interface ISingleton<T> where T : class
{
void SetSingleton(T _classType, GameObject _obj);
T GetInstance();
}
Singleton.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public abstract class Singleton<T> : MonoBehaviour , ISingleton<T> where T: class
{
public static T instance = default;
public void SetSingleton(T _class, GameObject _obj)
{
if (instance is null) instance = _class;
else if(instance.Equals(_class))
{
Debug.LogError("Unexpected Instancing Singleton Occuired! from " + gameObject.name);
Destroy(_obj);
return;
}
DontDestroyOnLoad(_obj);
}
public T GetInstance()
{
return instance;
}
}
Manager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Manager : Singleton<Manager>,IManager
{
public int data;
protected virtual void Awake()
{
Initialize();
}
public virtual void Initialize()
{
SetSingleton(this,this.gameObject);
}
}
GameManager
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameManager : Manager
{
public int HP,point;
protected override void Awake()
{
Initialize();
}
public override void Initialize()
{
SetSingleton(this, this.gameObject);
}
private void StartGame() => print("GameStart");
private void PauseGame() => print("Game Paused");
private void QuitGame() => Application.Quit();
}
Below is the rough structure of my code.
Aucun commentaire:
Enregistrer un commentaire