mercredi 25 octobre 2017

Access instance of containing class from instance of another class being contained

I'm creating a simple RPG game in C# using WPF, and have a Hero class which contains an instance of my Inventory class and an instance of my Equipment class. When a Hero selects any of their Item instances in their Inventory instance to equip, I want to be able to pass a reference back to the Hero instance to be equipped in their Equipment instance.

Right now I have only one Page where I let Heroes equip anything, but that's soon to change, and I was wondering if there's a way to make it work the way I want it to. I was considering passing the Hero instance as a parameter when instantiating the Equipment and Inventory instances, like so:

internal class Hero
{
    internal Equipment CurrentEquipment { get; set; }
    internal Inventory CurrentInventory { get; set; }

    internal void Equip(Item selectedItem)
    {
         //put in correct spot in Equipment
    }
}

internal class Inventory
{
    internal Hero Owner { get; set; }

    private void Equip()
    { 
        //remove from Inventory, send it to Hero instance to be equipped
    }

    public Inventory(Hero owner) => Owner = owner;
}

with my Equipment class having the same property and constructor, and wherever I instantiate Hero, I pass the reference to the containing Hero, like so:

Hero currentHero = new Hero();
currentHero.Inventory = new Inventory(currentHero);
currentHero.Equipment = new Equipment(currentHero);

so that I don't have to make so many calls to currentHero every time I want to do anything, I can just pass the Inventory instance to whatever Window I'm working on, the Inventory holding a reference to currentHero

_inventory.Equip(selectedItem)

is so much faster than my current method of calling in my actual build:

GameState.CurrentHero.Equipment.Equip(GameState.CurrentHero.Inventory.Items.Find(itm => itm.Name == whateverItem)

So, is there a better way of what I'm trying to do? What is it called when you pass a container object into an object it contains?

Aucun commentaire:

Enregistrer un commentaire