- Home /
Putting a Child Class into a List of Parent Type and then casting it back to a Child
I'm trying to set up an inventory system with a List of Inventory_Items to store them. However I want to use weapon or armor classes that inherit from Inventory_Items so they don't have worthless variables like ammo type on a sword or something. I have it set up, however, upon casting the Inventory_Items object in the list back into its original child class, all of the variables belonging to the child class are set to their default values. Is there a way for those variables to be recovered after being converted to a parent class?
//parent class
[System.Serializable]
public class Inventory_Item: MonoBehaviour
{ //data types
public Inventory_Item()
{
//constructor
}
}
//Child Class
[System.Serializable]
public class Player_Usable_Item : Inventory_Item
{
Player_Usable_Item() : base
}
//database class
public class Item_Database : MonoBehaviour {
[SerializeField]
public List<Inventory_Item> allItems = new List<Inventory_Item>();
void Awake ()
{
allItems.Add (new Inventory_Item());
allItems.Add ((Inventory_Item)new Player_Usable_Item());
}
}
//trying to access child variables
Player_Usable_Item test = (Player_Usable_Item)itemDatabase.allItems[3];
Debug.Log (childVariable + ""); //returns default values
Yes you could do that like this...
Inventory_Item i = itemDatabase.allItems[3];
Player_Usable_Item p = i as Player_Usable_Item;
if (p != null)
{
// do stuff with p
}
else
{
// it's not a Player_Usable_Item
}
However...
You don't need to cast a Player_Usable_Item to the parent class when adding it to the list. A Player_Usable_Item IS an Inventory_Item.
You've made Inventory_Item a $$anonymous$$onoBehaviour, so neither that nor the derived class can have a constructor (and hence can't be created in the way you're doing it in the Awake function).
I see. However, once converted all of the new variables belonging only to the child are still all set to their defaults. Is there no way to prevent this as the data is simply lost when it's first put in the parent list?
Not sure what you mean, the classes don't appear to have any member variables in the code you've shown. How are you changing the defaults?
You won't be losing data just by putting the references into a List.