#function inheritance and casting issue

1 messages · Page 1 of 1 (latest)

cedar rivet
#

howdy! need simple advice on something!
i plan to have multiple kinds of enemies that inherit from an enemy base class
when a player hits them
how do i call a method they have?
would i try to get the component of the base script they all inherit from?

glad walrus
#

So you want to essentially do this, right?
Hit an enemy, then call the respective TakeDamage() that is for the specific type?

cedar rivet
#

correct

glad walrus
#

Because if so, you're in luck

#

Interfaces are your friend

#

gimme a sec

cedar rivet
#

👍 thank you mr spamton g spamton

glad walrus
#

Essentially, make every enemy inherit from this as a start

{
    public abstract void TakeDamage();
}```
#

This means that every enemy that you have inherit from it must have a TakeDamage() function.

cedar rivet
#

okay, but then how do i treat a gameobject as an enemy and call that method>

#

like if i have a game object from a collision

glad walrus
#

just a sec, typing it up now

#

Enemy enemy = hit.GetComponent<Enemy>().TakeDamage();

Basically, what this does is, first you find out what object you hit, then call its damage function.

cedar rivet
#

okay thank you!

glad walrus
#

Embrace the power of polymorphism ⚡

#

Oh and just so you know, if you make an object inherit from Enemy, you MUST make sure it has a TakeDamage function on it.
Interfaces are kinda like a contract.

#

That say "this object must have all of my functions inside of it"

cedar rivet
#

awesome!