Efficient way to do this?

Some of the enemies in my game can’t use the base enemy script because they have mechanics too different from a normal enemy, which means I have to make a new script for each enemy that’s like this. So my problem is in killing the enemy because I need to destroy the script on them, but how do I know what enemy script they have? I could do something like this for each script

if ( enemy.GetComponent<FirstBoss>() )
{
    Destroy(enemy.GetComponent<FirstBoss>());
}

but obviously that is a horrible way to do it. How would I efficiently check for what script the enemy has in a sustainable way (sustainable as in I wouldn’t have to do any considerable work to make the code still work).

I would implement an interface. Then when you call GetComponent, call it on the interface. Your interface could even have the method that handles destroying the script.

2 Likes

This… WAAAY better than inheritance, and plus interfaces play super-nice with Unity Components.

Using Interfaces in Unity3D:

https://discussions.unity.com/t/797745/2

https://discussions.unity.com/t/807699/2

Check Youtube for other tutorials about interfaces and working in Unity3D. It’s a pretty powerful combination.

1 Like