简体   繁体   中英

Inherit from a Singleton and a base class

In my Unity game, I have one player and one enemy (it's a card game so this is always true). I use a basic Singleton base class to access them from any sub-system in the game, like this:

public abstract class Singleton<T> : MonoBehaviour where T : Component
{
    public static T instance;

    protected virtual void Awake()
    {
        if (instance != null) {
            string typename = typeof(T).Name;
            Debug.LogWarning($"More that one instance of {typename} found.");
        }
        instance = this as T;
    }
}

public class Player : Singleton<Player>
{
    public void DoSomething();
}

public class Enemy : Singleton<Enemy>
{
    public void DoSomething();
}

public class OtherPartOfGame : MonoBehaviour
{
    void Start() {
        Player.instance.DoSomething();
        Enemy.instance.DoSomething();
    }
}

But I want to pull out some common functionality into a base class CharacterBase. Of course normally I'd just do this:

public abstract class CharacterBase : MonoBehaviour
{
    public abstract void DoSomething();
}

public class Player : CharacterBase
{
    public override void DoSomething() {}
}

public class Enemy : CharacterBase
{
    public override void DoSomething() {}
}

But how do I also keep my generic Singleton in the mix, without using multiple inheritance?

Well the easiest way would be to just let your CharacterBase class inherit from Singleton like this

public abstract class CharacterBase<T> : Singleton<T> where T : Component
{
    public abstract void DoSomething();
}

and then do

public class Player : CharacterBase<Player>
{
    public override void DoSomething() { ... }
}

public class Enemy : CharacterBase<Enemy>
{
    public override void DoSomething() { ... }
}

Everything else would just complicate it for no good reason.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM