Hello,

I'm having a bit of trouble with inheritance I was hoping one of you could help with.

I have a base clase; BaseGameEntity.

There are two classes which inherit from this, Drop and DropGuide.

I have an entity manager that stores all of the instance of Drop/DropGuide in a List<BaseGameEntity>.

The problem is when I use access an element in this list I can only seem to get to the "BaseGameEntity" parts of the object, how from there do I access the Drop/DropGuide that inherit from it?

Use the "as" keyword to cast them (I ignored the list portion for simplicity):

BaseGameEntity bge = new Drop();
(bge as Drop).DropMethod();

or you can use the old fashioned

((Drop) bge).DropMethod();

Edited 6 Years Ago by jonsca: n/a

Use the "as" keyword to cast them (I ignored the list portion for simplicity):

BaseGameEntity bge = new Drop();
(bge as Drop).DropMethod();

or you can use the old fashioned

((Drop) bge).DropMethod();

Thanks, that's perfect.

Is there also a way to go through the list and manipulate each Drop whilst ignoring the DropGuides?

At the moment I've added a variable "type" and then used a for loop to go through each item then an if to check the type of object it is, this works perfectly well just seems there may be a more elegant solution I'm just not aware of.

I had initially thought a statement along the lines of foreach(Drop drop in entityList) would work - but that seems to take the dropguides and treat them as drops causing an error.

Edited 6 Years Ago by MrMee: n/a

Yep, you can shift to using "is"

foreach(BaseGameEntity bge in entityList)
    if(entity is Drop)
       //process it

Embaressingly simple!

Thanks again.

Nah, they're just new for a lot of people. They play very well with interfaces if you go down that road at a later time.

Never a problem.

This question has already been answered. Start a new discussion instead.