GetComponent of an inherited class

I have a base class that is inherited by some other controllers:

AiController

public class AiController : MonoBehaviour
{
public string myTeam;
// Lots of other stuff...
}

When an object is hit by a Physics2D.OverlapCircleAll to find nearby enemies, I want to be able to tell which Team this AI is on as I don’t want friendly fire. I can’t use Tag as I use tag to differentiate different unit types that are shared between teams.

I have tried gameObject.GetComponent() but it returns null as it will actually be RangedAiController or another that inherits from AI Controller.

Is there a clean way to get the myTeam property value from these collisions without doing this:

    void FindNearbyEnemies()
    {
       Collider2D[] collisions = Physics2D.OverlapCircleAll(transform.position, 10f);
        List<GameObject> enemies = new List<GameObject>();
        for (int i = 0; i < collisions.Length; i++)
        {          
            if (collisions[i].gameObject.GetComponent<RangedAIController>() != null)
            {
                if (collisions[i].gameObject.GetComponent<RangedAIController>().myTeam == enemyTeam)
                    enemies.Add(collisions[i].gameObject);
            }
            else if (collisions[i].gameObject.GetComponent<ConverterAiController>() != null)
            {
                if (collisions[i].gameObject.GetComponent<ConverterAiController>().myTeam == enemyTeam)
                    enemies.Add(collisions[i].gameObject);
            }
            else if (collisions[i].gameObject.GetComponent<Base>() != null)
            {
                if (collisions[i].gameObject.GetComponent<Base>().myTeam == enemyTeam)
                    enemies.Add(collisions[i].gameObject);
            }
        }
        potentialTargets = enemies;
    }

Any help would be greatly appreciated.

You can actually use interfaces for this purpose.

public interface ITeamBelonger
{
   string GetTeam();
}

Then any of your Monobehaviors can implement that ITeamBelonger interface.

When you want to use it,

var teamBelonger = gameObject.GetComponent<ITeamBelonger>();

And if it comes back non-null, you call the GetTeam() method.

2 Likes