Can we use interface there?
example:
public interface IHitable
{
void Hit(float damage);
}
… .TryGetComponent(out IHitable hitable) …
Add it to every object we can hit
Can we use interface there?
example:
public interface IHitable
{
void Hit(float damage);
}
… .TryGetComponent(out IHitable hitable) …
Add it to every object we can hit
Yes, this would be a good use case for an interface… In this case, since both are using Damage
public interface IHitable
{
void Damage(float damage);
}
And then
if(collider.TryGetComponent(out IHitable hitable) //The compiler will infer the <IHitable> for the TryGetComponent based on the out Parameter
{
hitable.Damage(damageAmount);
}
I actually did this, but I called it IDestructable
public interface IDestructable
{
Vector3 GetWorldPosition();
void DealDamage(int damage);
}
I added GetWorldPosition
(which is probably unnecessary) because I calculated damage based on the distance from the grenade explosion, for example
if (collider.TryGetComponent(out IDestructable destructable))
{
var damage = CalculateDamageBasedOnDistance(_targetPosition, destructable.GetWorldPosition());
destructable.DealDamage(damage);
}