Im making a game with many attack types. Each attack is a script that has 4 segments. Get targets in range, doTargeting, doAttack, doAIAttack.
So in the main attack script everytime I have to get the range of a weapon or ability I do this.
if (targetingType == "Sword")
{
GetComponent<Sword>().Range();
}
else if (targetingType == "Bomb")
{
GetComponent<Bomb>().Range();
}
else if (targetingType == "Detonate")
{
GetComponent<Detonate>().Range();
}
etc etc etc.
Than the same for Targeting, than again for Attacking. Is here a way to just refference the scripts via a String. So I could use something like GetComponent<“targetingType”>().Range();
In theory you can get a component by using a System.Type reference which you could get through a string. However if you do GetComponent would return a “Component” reference. So the reference does not have the specific type you’re looking for and doesn’t have a Range method you could call. This is all possible with reflection but is slow, has a lot of overhead and is error prone.
A better approach would be that you let all those classes (Sword, Bomb, Detonate) implement an interface like
public interface IRangeable
{
void Range();
}
So the class would look like this:
public class Sword : MonoBehaviour, IRangeable
{
Now you can simply do
if (TryGetComponent<IRangeable>(out IRangeable rangeable))
{
rangeable.Range();
}
This would work for any class that implements this interface. So I would highly recommend to choose a better, more descriptive name for the interface. You may also add additional methods or properties to the interface if you need to. Keep in mind that an interface is essentially a contract that a class has to fulfill when it implements that interface. So the class must implement all methods / properties defined in the interface.