Hey guys, so I am creating a general inventory adding function (basically, it receives an input and will create an instance of a script that will be a new weapon in the first slot of the player’s inventory, which is an array of objects). My problem is that, the function is inside the character class and I don’t know how to pass a type as a parameter in this function and end up with an object/instance of that type in the person’s inventory. I’ve tried using System.Type for a parameter, referenced this old thread here (How do I pass an Object type to a function in c#? - Unity Engine - Unity Discussions) which seemed like what I was trying to do but I just can’t get it to work for me, and everything else under the sun. I attached some of my code below to give a better idea of my problem. Any help or a push in the right direction would be immensely appreciated! Thanks guys!
public class BaseCharacterClass {
// defining everything for every base character (i.e. stats, description, movement allocation, etc.)
protected Object[] characterWeaponInventory = new Object[4];
public Object[] CharacterWeaponInventory
{
get
{ return characterWeaponInventory; }
}
}
And this is the code that is giving me trouble (it’s inside the character class I posted above and references those variables/arrays) (also references item classes that I haven’t included here):
public void AddItemToInventory(Object newAddedItem /* this parameter is the one giving me trouble */)
{
if (newAddedItem.GetType().IsAssignableFrom(typeof(BaseItem)))
{
if (newAddedItem.GetType().IsSubclassOf(typeof(BaseStatsWeaponItem)) && this.CharacterWeaponInventory.Length < 4)
{
int slotToBeAddedTo = this.CharacterWeaponInventory.Length;
this.CharacterWeaponInventory[slotToBeAddedTo] = newAddedItem;
}
if (newAddedItem.GetType().IsSubclassOf(typeof(BasePotion)) || newAddedItem.GetType().IsSubclassOf(typeof(BasePermabuff)) || newAddedItem.GetType().IsSubclassOf(typeof(BasePromotionItem)) || newAddedItem.GetType().IsSubclassOf(typeof(BaseHeldEffectItem)) || newAddedItem.GetType().IsSubclassOf(typeof(BaseLiquidAssetItem)) || newAddedItem.GetType().IsSubclassOf(typeof(BaseKeyItem)) && this.CharacterItemsInventory.Length < 3)
{
int otherSlotToBeAddedTo = this.CharacterItemsInventory.Length;
this.CharacterWeaponInventory[otherSlotToBeAddedTo] = newAddedItem;
}
}
}