- Home /
How to ignore base class?
I have an inventory system where every item (melee weapons, potions, ranged weapons, etc.) inherit a base class called BaseItem. They eventually branch off into different inheritances (i.e: BaseItem-AbstractWeapon-MeleeWeapon or BaseItem-AbstractWeapon -RangedWeapon). Items in the inventory are stored in one Item list:
public static List<Item> inventoryItems;
Whenever an item in the GUI display of the inventory is pressed it returns an item from the list and performs a task:
if (GUI.Button (new Rect (0, 50, 100, 100), inventoryItems [0].Icon)) {
ItemPressed (inventoryItems [0]);
}
}
void ItemPressed(Item item){
//insert task here
}
The problem is I want the task performed to be specific to the item being pressed. For example, if the item inherits from AbstractWeapon I want the weapon to be equipped, but the item doesn't return as an AbstractWeapon or any other class except BaseItem. Is there any way to specify the classes being inherited? Answers Appreciated.
Answer by perchik · Apr 07, 2014 at 09:02 PM
Yep, override. The base class needs to have the function either marked abstract
or virtual
(abstract if it doesn't implement it at all, virtual if it implements but you want to override)
class Shape{
public abstract float getArea();
}
class Square:Shape{
public override float getArea(){
//do something
}
}
OR
class Shape{
protected string name;
public virtual void setName(string n){
name = n;
}
}
class Square:Shape{
public override void setName(string n){
name = "sq"+n;
//also could call the base fcn:
base.setName(n);
}
}
The first example prohibits you from instantiating a Shape
class, because getArea() isn't implemented. The second example will let you have both Shapes and Squares in your project