General class for all script-classes?

My problem is that in my game i have three different enemies, a skeleton, a skeleton mage and a scorpion. On each of those i have a common script called “EnemyBaseScript”. This script checks by name which enemy it is and calls “Scorpion.function”, “Skeleton.function” or “SkeletonMage.function” with a switch case.

private void attackPlayer()
{
switch (Enemy_)
{
case 1:
StartCoroutine(SkeletonNormal.attack());
break;

case 2:
StartCoroutine(SkeletonMage.attack());
break;

case 3:
StartCoroutine(Scorpion.attack());
break;
}
}

I think this makes bad performance, especially if i would like to expand my game with say 10 different enemies?

  • Is there a way to have general class for all the scripts so i can do something like this:

private commonClass thisEnemy;

if(this.name == “Skeleton”)
{
thisEnemy = this.getComponent();
}
else if(this.name == “Scorpion”)
{
thisEnemy = this.getComponent();
}

Inheritance and or interfaces.

Thanks for the answer. I have seen the links but i still don’t see how my problem can be solves using inheritance and/or interfacing? Can you give me a more detailed answer?

  • Thanks
public abstract class BaseEnemy
{
    public abstract void Attack();
}

public class Skeleton: BaseEnemy
{
    override public void Attack()
    {
        //Skeletonattack code
    }
}

public class Scorpion: BaseEnemy
{
    override public void Attack()
    {
        //Scorpionattack code
    }
}

Then you can do something like:

BaseEnemy enemy;

gameObject.GetComponent<BaseEnemy>().Attack();

Oh i see! - Thanks a lot Guzzo, really helped me!