在《Game development patterns with unity》一书中,有这样一段代码
public class Singleton<T> : MonoBehaviour where T : Component
{
private static T _instance;
public static T Instance => _instance;
public virtual void Awake()
{
if (_instance == null)
{
_instance = this as T;
}
else
{
Destroy(gameObject);
}
}
}
c#如何强制转换Singleton
Singleton类不能单独使用。你可以从Singleton中继承你想要创建的类,比如GameManager,并使用它。
public class GameManager : Singleton<GameManager>
{
public void ManagerMethod()
{
// your code.
}
}
public class MyClass
{
void Do()
{
GameManager.Instance.ManagerMethod();
}
}