- Home /
Class inheritance for Item system question: Instance needs to be both Weapon and Ammo subclass
I have three classes: a base Item class as well as two classes inheriting from it: Weapon and Ammo.
public class Item {
public string name;
public Texture2D icon;
}
public class Weapon : Item {
public int ammo_max;
public int damage;
}
public class Ammo : Item {
public int amount;
}
So far, so good. Now my problem: I want to have grenades that can be both: Weapon and Ammo. They could be loaded as Ammo for a grenade launcher (Weapon) or they could be a Weapon themselves (thrown). Is there an elegant way of accomplishing this, or have I walled myself in with my item inheritance? :)
Answer by IgorAherne · Feb 16, 2017 at 09:59 PM
You can only inherit from one class ever, but can also inherit from multiple interfaces at the same time
Interfaces are just forward-declarations of classes's functionality, simply giving a guarantee that particular functoins can be invoked on your objects who use such an interface.
Answer by anathemort · Feb 17, 2017 at 08:25 AM
If your Ammo
class is going to stay that simple, you could change it to be something like this
interface IAmmoCommidity
{
int Amount { get; }
void Consume();
void Consume(int amount);
}
Then your Grenade
would extend Weapon
and implement the new IAmmoCommodity
interface. If you have lots (or really, more than one) of different types of mixed weapon/ammo objects, you could have a WeaponCommodity
intermediary class to handle the default implementation of the interface.
Your answer
![](https://koobas.hobune.stream/wayback/20220612111253im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Working with Items and Class Inheritance for an RPG Item Database 1 Answer
[C#]Inventory script help. 3 Answers
Inventory AddItem help 1 Answer
Can't seem to get my item hotbar working correctly. 0 Answers