'How can I access a function with the same name held on multiple different scripts in Unity C#
I'm working in Unity on a game with a spell casting system where I have a casting manager script that has a game object list of all the equipped spells (called spells and selectedSpell is just an int that determines which spell in the list is selected so I can cycle through them) and then on each game object/spell, I have a script that will do different things based on the spell. Each game object only has the one script, a sprite renderer, and a transform. The issue I'm having is here:
//Cast manager Script
if (Input.GetKeyUp("c"))
{
Debug.Log($"Cast {spells[selectedSpell]}");
spells[selectedSpell].GetComponent<FireballSpell>().Cast();
}
The Cast function contained in the script I'm trying to access looks like this:
///Water spell named "WaterSpell"
public void Cast()
{
Debug.Log("Sploosh");
}
//FireballSpell
public void Cast()
{
Debug.Log("Kabloom");
}
I threw in a script for now (the "FireballSpell") and it accesses Cast() just fine when I've got the fireball spell selected, however I'm not sure how to access Cast() from my "WaterSpell" for example. I tried doing GetComponent(nameof($"{spells[selectedSpell]}")).Cast() because I've been giving the scripts the same name as the game object, but I just get an error saying, "component does not contain a definition for cast". I'm not really sure how to proceed with this aside from making a bunch of "if selected spell is named x look for this script" for each spell but while it would work, I feel like it could be much more efficient and I don't want to have to worry about adding to the casting manager script if I decide to add more spells down the line.
Thanks in advance to anyone who stumbles on this. If more information is needed I'll try to provide it.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|

