GetComponent( ) and Polymorphism
I have a EnemyGrunt
class that inherits Enemy
class. I'm trying to call a method from the Enemy
class like this, when casting the overlap on a game object with the EnemyGrunt
script:
numberOfLayersDetected = Physics2D.OverlapBoxNonAlloc(meleeAttackSpawnSpot.position,
new Vector2(meleeAttackBoxRadiusX, meleeAttackBoxRadiusY), 0, castResults, 1 << LayerMask.NameToLayer("Enemy"));
if (numberOfLayersDetected > 0) {
for (int i = 0; i < castResults.Length; i++) {
Enemy currentEnemy = castResults[i].gameObject.GetComponent<Enemy>();
currentEnemy.SufferDamage(meleeDamage);
}
}
However, the currentEnemy
variable doesn't receive anything from the GetComponent()
. Probably I'm doing something wrong, so I ask you: how can I inflict damage in any type of object that inherits from Enemy
class?
Answer by Casiell · Mar 08, 2019 at 09:26 AM
GetComponent works with polymorphism, so the problem must be somewhere else.
Are you sure your EnemyGrunt script is placed on the same object as his collider? Are you sure you are even getting expected results from your OverlapBox?
Thanks for tips, it really helped solving the problem. The collider is a child of the object containing the script and I modified the script to filter it as much as possible. That's how it looks like now:
if (numberOfLayersDetected > 0) {
for (int i = 0; i < numberOfLayersDetected; i++) {
Enemy currentEnemy = castResults[i].transform.GetComponentInParent<Enemy>();
if (currentEnemy is Enemy) {
currentEnemy.SufferDamage(meleeDamage);
}
}
}
Happy it works now. Also I believe that replacing "currentEnemy is Enemy" with "currentEnemy != null" would be better as being null is the only situation where "currentEnemy is Enemy" could be false