I’m learning C# and I’m trying to make a game and I have a problem. I have two classes that I call Item and Weapon, Weapon looks something like this:
class Weapon : Item
{
int damage;
int durability;
public void asd()
{
Weapon shortSword = new Weapon();
shortSword.dmg = 5;
shortSword.durability = 20;
Weapon woodenBow = new Weapon();
woodenBow.dmg = 3;
woodenBow.durability = 15;
}
}
Then I have another class containing different methods, one of them is called when the player walks on an item and its supposed to randomize that item. But I can’t reach the objects in Weapon from this other class. How do I reach them, or solve this problem?
There is a problem with your design. The method that creates weapons shouldn’t be an instance method on the
Weaponclass. It could perhaps be a static method, or perhaps even a method on some other class.Your method should return the weapons in a collection or as an
IEnumerable.I also used the object initializer syntax to make the code more concise, and tidied up some of your method/property naming.