You can't do this without reflection which is slow depending on how often this is done.
To simplify your code, you have to use Dictionary
or provide a way to translate the _ID
to your function. Since you're yielding each coroutine function call, you have to store each function as IEnumerator
so that you can yield it.
The Dictionary:
Dictionary<int, IEnumerator> idToDict = new Dictionary<int, IEnumerator>();
Function to add the IDs and it's functions to the Dictionary. Call this function from the Awake
or Start
function.
void InitIDs()
{
idToDict.Add(1, Elements[5].GetComponent<ID1>().StartAttack(EnemysInBattle, HeroesInBattle, Attacker));
idToDict.Add(2, Elements[5].GetComponent<ID2>().StartAttack(EnemysInBattle, HeroesInBattle, Attacker));
idToDict.Add(3, Elements[5].GetComponent<ID3>().StartAttack(EnemysInBattle, HeroesInBattle, Attacker));
idToDict.Add(4, Elements[5].GetComponent<ID4>().StartAttack(EnemysInBattle, HeroesInBattle, Attacker));
idToDict.Add(5, Elements[5].GetComponent<ID5>().StartAttack(EnemysInBattle, HeroesInBattle, Attacker));
}
To use it, check for the _ID
value in the Dictionary
. If it exist, execute the coroutine function paired with it then yield each one just like you did in your original code:
int _ID = Attacker.GetComponent<BaseHeroStats>().ID_Model;
IEnumerator action;
//Check if the function name exist, start it then yield it
if (idToDict.TryGetValue(_ID, out action))
{
//Execute the approprite code
yield return StartCoroutine(action);
}
EDIT:
Another option is to replace your _ID
with string
. That string should instead contain the name of the script. You can then use reflection and the dynamic
keyword to call the coroutine
function. So, int _ID
should now be string _ID
which contains the name of the script. This also means that the ID_Model
variable in your BaseHeroStats
class should now be a string
.
For example something like this:
string _ID = "ID2";
Type type = Type.GetType(_ID);
Component ids = GetComponent(type);
dynamic val = Convert.ChangeType(ids, type);
StartCoroutine(val.StartAttack());
Or in your own code example:
string _ID = Attacker.GetComponent<BaseHeroStats>().ID_Model;
Type type = Type.GetType(_ID);
Component ids = Elements[5].GetComponent(type);
dynamic val = Convert.ChangeType(ids, type);
yield return StartCoroutine(val.StartAttack(EnemysInBattle, HeroesInBattle, Attacker));
You must enable the .NET 4.6 to use the dynamic
keyword. See this post. This should work but use the Dictionary version of this code because it's faster.