I'm a beginner in C# and trying to implement a player, an item interface, and some kind of storage system (for player inventory, NPC inventory/drop list, and storage like chests), and having some trouble implementing it in a way that requires the least work for a large amount of class types (and instances).
This is my current Player class:
namespace RogueBase.Classes
{
public class Player
{
public Iitem[] inventory { get; set; }
private int _hp;
public int hp
{
get { return _hp; }
set
{
if (value <= 0) _hp = 0;
else if (value > 100) _hp = 100;
else _hp = value;
}
}
public Player()
{
hp = 100;
}
}
}
And my Storage class:
using RogueBase.Interfaces;
namespace RogueBase.Classes
{
public class Storage
{
public Storage(int capacity)
{
inventory = new Iitem[capacity];
}
public bool Add(Iitem newItem)
{
for (int i = 0; i < inventory.Length; i++) // check each slot
{
if (inventory[i] as Iitem != null) { continue; } // skip items
inventory[i] = newItem; // assign item to empty slot
return true; // report success
}
return false; // inventory full
}
public bool Remove(Iitem targetItem)
{
for (int i = 0; i < inventory.Length; i++) // check each slot
{
if(inventory[i] == targetItem) // when match is found
{
inventory[i] = null; // remove it
return true; // report success
}
}
return false; // no item found
}
}
}
Item interface (just for reference):
namespace RogueBase.Interfaces
{
public interface Iitem
{
string name { get; set; }
int sellValue { get; set; }
bool consumable { get; set; }
void Equip();
void Sell();
void Consume();
}
}
The problem right now is that every time I want to create a new inventory for something, I need to prepare a variable for it (not a problem when it comes to the player), but I'd like to be able to create friendly and hostile NPCs on demand with their own unique inventory that could be randomly generated,
In order to do this, is it my only option to turn the Storage class into an interface and copypaste the functions for every NPC/storage type? Or can I somehow turn the Add/Remove functions static? If I try to do it right now I get an error:
An object reference is required for the non-static field, method, or property 'Storage.inventory'
Edit; Specified question:
How can I access Iitem[] inventory
in class Player
to be used in class Storage
's methods?
Storage
class, like you had before. And let the player have variable ofStorage
type, for the code example see my updated answer. \$\endgroup\$