Home > Net >  Is a good practice to create one prefab and one script per enemy type?
Is a good practice to create one prefab and one script per enemy type?

Time:02-21

I'm in the process of creating the enemy for my tower defense game.

I want one enemy to be tanky (lots of health) one enemy to be fast one enemy to cast spells to boost other enemies

Based on my research, I could create an enemy base class, then create a script for each enemy type (Tank, Speed, Enchanter). I would then need to place them on each respective prefab but I'm wondering whether this is good practice? Let's say that I have 100 enemy types, do I need to create 100 scripts and prefabs for it?


On another note, I'm planning to use scriptable objects for the enemy stats but I'm a bit confused on how to implement it. I would create one enemy prefab, feed it the scriptable object of my enemy (e.g some SO has lots of health, some has lots of speed) but I'm not too sure how can I implement different behaviors for each enemy type.

Thank you!

CodePudding user response:

You can create a scriptable object like this:

[CreateAssetMenu(fileName = "Enemy", menuName = "Enemy")]
public class EnemyData : ScriptableObject
{
    public int Health;
}

you can define more variables as you want. You can create multiple EnemyData from Create menu and set different values for each enemy.

Then create an enemy class like this.

public class Enemy : Monobehavior
{
    public EnemyData data;
}

You can load this data from different ways. The simplest way could be like this for Enemy1:

public class Enemy : Monobehavior
{
    public EnemyData data;

    private Awake()
    {
        data = (EnemyData)Resources.Load("Enemies/Enemy1", typeof(EnemyData));
    }
}

You can access to each value like this:

data.Health

For this, you should put your enemy objects in Resource/Enemies folder. You can define name or id for different enemies, so loading could be easier.

I hope this brings an idea for you.

CodePudding user response:

You could create an Enemy base class and expose the speed and health as public properties so that way you could configure each instance differently. I would also consider creating a separate script that's sole purpose is 'casting spells to boost other enemies' also a separate script that fires projectiles with customizable damage, etc. By separating the responsibilites, you make your system modular and you can basically put together any combination you want by adding a behavior to a prefab.

  • Related