Hello, I’m currently trying to create an inventory for my 2D hack’n’slash game. I’ve tried creating an abstract class for ‘Item’ and then deriving into different classes for each item type. Like so:
public abstract class Item {
// Item name
public string Name;
// Usage effect
public abstract void Action(GameObject go);
}
public class HolyGrail : Item {
public HolyGrail ()
{
}
string Name = "Holy Grail";
override public void Action(GameObject go)
{
go.GetComponent<Pstats> ().health += 30;
}
}
But when I try to create a new HolyGrail it becomes null, which makes it impossible for me to use it. Do I try a different approach or what do I do?
Your can’t “override” variables. You effectively are creating a new Name variable in your subclass so the class will have two different Name variables. You should initialize the inherited Name variable in your constructor:
public class HolyGrail : Item
{
public HolyGrail ()
{
Name = "Holy Grail";
}
public override void Action(GameObject go)
{
go.GetComponent<Pstats> ().health += 30;
}
}
If you do this:
Item someItem = new HolyGrail();
Debug.Log("Item name: " + someItem.Name);
It should print the name just fine. If someItem itself becomes “null” after you create your HolyGrail with new, you probably have derived your Item class from UnityEngine.Object (directly or indirectly). If the Item class looks like you showed us it should work just fine that way.