Why does your gun check every type?

Enemy, barrel, window. Every new thing is another if.

Why does your gun check every type?

The problem

A type check for every target.

void OnHit( object thing ){    if ( thing is Enemy e ) e.TakeDamage( 10 );    else if ( thing is Barrel b ) b.Explode();    else if ( thing is Window w ) w.Shatter();    // a crate? go back and edit the gun}

The gun has to know every type in the game. Adding a crate means editing the gun.

The fix

Ask what it can do, not what it is.

An interface is a promise: anything that implements IDamageable has a TakeDamage method.

EnemyBarrelWindow→IDamageable

The fix in code

One check, any target.

public interface IDamageable{    void TakeDamage( int amount );} public class Barrel : IDamageable{    public void TakeDamage( int amount ) => Explode();} if ( thing is IDamageable d ) d.TakeDamage( 10 );

Each type decides what damage means. The gun never changes again.

In Unity

TryGetComponent finds interfaces too.

if ( hit.collider.TryGetComponent( out IDamageable d ) )    d.TakeDamage( 10 );

Any component that implements it is found, whatever its class is called.

The rule

Code against what it can do.

The promise
interface IDamageable
Keep it
class Barrel : IDamageable
Use it
is IDamageable d