vendredi 23 septembre 2016

Instantiate a Singleton in c#

I'm trying to instantiate an object with a singleton in c#.

    private static Mario __instance;
    public static Mario Instance
    {
        get
        {
            if (__instance == null)
            {
                __instance = new Mario(); //TODO correct this vector
            }
            return __instance;
        }
    }

    public Mario() 
    {
        position = Vector2.Zero;
        theatre = XNATheatre.Theatre;
        ActionState = new IdleState();
        PreviousState = ActionState;
        ActionState.Enter(null);
        isFacingRight = true;
    }

I also have an idlestate class that is being instantiated in mario's constructor:

    public IdleState()
    {
        mario = Mario.Instance;
        Console.WriteLine(mario);
    }

What seems to be happening is the _instance variable in my singleton always remains null, therefore it keeps returning new instances of mario, exactly the opposite of what I want it to do. I'm not exactly sure how to get around this.

Aucun commentaire:

Enregistrer un commentaire