I have a character script that has a list of abilities it can use. This list will vary from character to character and even over time. I’m wondering how I can tell a character which abilities it has where an ability is essentially a class that does something (like tell the character to make a specific attack). This is for a turn based game. The issue I have now is that I don’t want to create an empty game object for each ability and add it to the character. For instance, I have one character fighting 3 others and all of them can make a basic attack. So each would have that ability and when it is chosen will do stuff according to that ability. Any help would be appreciated.
Hi!
One of the way to achieve this is that your ability should have core abstract class that has basic functions and values that each other ability will have as well.
Something like this:
using UnityEngine;
public abstract class CharacterAbility : MonoBehaviour
{
public abstract void TriggerAbility();
}
The ability itself inherit from the abstarct class and overrides the abstract functions to create specific behaviour for the ability.
public class FirstAbility : CharacterAbility
{
public override void TriggerAbility()
{
// Code for this ability
}
}
To store all abilities you will have 1 script that has array of them, like this:
public class AbilityHolder : MonoBehaviour
{
public CharacterAbility[] charAbilities; // All abilities
}
Therefore your Character class only need reference to AbilityHolder to access abilities and List of indexes of learned abilities. Something like this:
using System.Collections.Generic;
using UnityEngine;
public class CharacterCont : MonoBehaviour
{
public AbilityHolder s_AbilityHolder;
/* Adjustable list of character abilities that related to charAbilities in s_AbilityHolder */
List<int> l_CharAbilities = new List<int>();
private void Update()
{
if (/*something*/)
s_AbilityHolder.charAbilities[l_CharAbilities[0]].TriggerAbility();
if (/*something else*/)
s_AbilityHolder.charAbilities[l_CharAbilities[1]].TriggerAbility();
}
void AddAbility(int abilityIndex)
{
l_CharAbilities.Add(abilityIndex);
}
void RemoveAbility(int abilityIndex)
{
for(int i = 0; i < l_CharAbilities.Count; i++)
{
if (l_CharAbilities *== abilityIndex)*
{
l_CharAbilities.Remove(i);
return;
}
}
}
}
----------
That how the base of it could look like.
There is good official tutorial about Ability System, that might help you further as well, you can check it out here: Create an Ability System with Scriptable Objects - Unity Learn
----------
Hope it helps.