Reputation: 2679
I have a bullet game object that detects enemies via OnTriggerEnter2D()
. This was working perfectly until I added different enemy types:
private void OnTriggerEnter2D(Collider2D collision)
{
Enemy enemy = collision.GetComponent<Enemy>();
if (enemy != null)
{
enemy.Destroy();
GameObject effect_ = Instantiate(bulletEffect, transform.position, transform.rotation);
Destroy(effect_, 0.5f);
Destroy(gameObject);
}
}
So simply if the bullet collides with Enemy()
then it should call its Destroy()
method.
The problem is that now I have added multiple enemies in my game, for example there is an enemy with the class name Runner()
with its own death method.
I can add an if condition and cycle through every enemy type but that will become tedious after more enemies are added.
Whats the best way of doing this?
Thanks
Upvotes: 0
Views: 210
Reputation: 5035
If all your enemies inherit from the same base class, make the death method virtual, and override it in child classes.
Alternative is to create an interface, and make your components implement that interface
interface IDeath
{
void OnDeath();
}
than when the collision happens you can do GetComponent< IDeath >() and get a reference to an object that does have this method, even if it doesnt inherit from anything (well it needs to inherit MonoBehaviour but thats it)
Upvotes: 0
Reputation: 807
Create a script called 'DamageBehavior'. Give that script a public function called 'TakeDamage'. Attach that script to each type of enemy so that they may each implement it differently. Then in your OnTriggerEnter2D function, regardless of the type of enemy that's been collided with, call its TakeDamage function.
private void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("Enemy"))
{
other.GetComponent<DamageBehavior>().TakeDamage();
}
}
Upvotes: 1
Reputation: 15941
private void OnTriggerEnter2D(Collider2D collision)
{
Enemy enemy = collision.GetComponent<Enemy>();
if (enemy != null)
{
enemy.DoDeathEffects(); //you will need to create this function.
Destroy(gameObject);
}
}
Your bullet should never decide what an enemy does when it does, that's the purview of the enemy. As you want your various enemies to have different behaviors, this means you will need to subclass the Enemy
class and the DoDeathEffects()
method should be both public
and virtual
.
Upvotes: 4