Store multiple inherited classes and keep their custom variable stored

I would like to do a list like :

List<Item> items = new List<Item>();

With all differents types of items that inherit from the main “ITEM” class

potion : item
food : item
material : item

Each class has it’s own parameters and properties like potion has fillAmount etc… that are set to a random number each time to scene starts.

void Start(){
     Potion p = gameObject.AddComponent<Potion>();
     p.fillAmount = Random.Range(5, 50);
}

What I’ve seen is that if get an Item back like :

if(item[0] is potion){
     print((Potion)item[0].fillAmount);
}

But this returns zero, any help?
Can’t this list store custom child class parameters?

Are you actually adding the Potion (p) that you create in Start() to your item array? Also, when are you printing the fillAmount? Keep in mind that Start() is not called immediately when you create a MonoBehaviour, thats what Awake() is for.

1 Answer

1

Are you missing a “s” in “item” name? List is items and not item.
I think you can compare just the types in this specific case.

if(items[0].GetType() == typeof(potion))
{
print((potion)items[0].fillAmount);
}

Dont forget to populate the list anyway.

you're right. I just tried it and it doesn't work, because the collision module negates the effect of the velocity module. in addition to my previous suggestion, i think you could try adding a script to set the particle velocity to 0 via script each frame. i.e.(ps.GetParticles(particles), particles*.velocity = Vector3.zero; ps.SetParticles(particles)). but if that doesn't work, i'm out of ideas...*