I am creating a 2D platformer where there will be multiple enemies, each with different spells they can cast. I’m trying to create an extensible system where I can easily create custom code for each spell (fire wave vs. bullet shooting toward enemy, vs AoE ability, etc.).
Here’s where I’m at right now:
- I have an EnemyAttackComponent class (monobehavior) that checks if the enemy can attack, if it’s in attack range, and also an abstract Attack class.
- I have a SpellAttack class that I derives from the above AttackComponent class which overrides the Attack method (see below
public class SpellAttack : EnemyAttackComponent
{
public List<Spell> spells;
public int spellSelector;
public override void Attack(GameObject target) {
if (CanAttack(target)) {
GameObject spellCast = Instantiate(spells[spellSelector].spellPrefab, transform.position, Quaternion.identity);
}
}
}
- I have a Spell ScriptableObject which contains the spell name, the spell prefab and the amount of damage the spell does. I read that I can put functions in here to override as well (such as movement), but I’m not sure if that’s a good idea.
- Finally, the prefab itself which has a script on it that controls the behavior of the used spell.
My Question:
I want to create multiple spells like I mentioned earlier. What is the best way to select which spell the enemy needs to attack? Surely there’s a better way than a switch statement in the SpellAttack code above. Does the way I’m structuring this spell system sound okay? Is there anything you would change?
Additionally, what about putting methods into my Scriptable Objects? In that case, I’d have to derive from that scriptable object class. Without deriving from monobehavior, how can I update the transform, etc.?
For reference, here is my Spell SO. I do not currently use the virtual MoveSpell method right now, because my spell script itself relies on deriving from monobehavior to move:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(fileName = "New Spell", menuName = "Spell")]
public class Spell : ScriptableObject
{
public string spellName;
public GameObject spellPrefab;
public float damage;
public virtual void MoveSpell(GameObject target) {
}
}
Thank you for the help! I’m just a few months into learning Unity and I’ve purchased a Udemy course on inheritance and composition. Hoping that will help me understand this more.