2020년 8월 22일 토요일

[Unity] Interface, 유니티 인터페이스 사용예제


인터페이스를 사용하면 이런 코드를

public class Bullet : MonoBehaviour{

    private void OnTriggerEnter2D(Collider2D collider)
    {
        Enemy enemy = collider.GetComponent<Enemy>();
        if(enemy != null)
        {
            //Hit a Enemy
            enemy.Damage();            
        }

        Crate crate = collider.GetComponent<Crate>();
        if(crate != null)
        {
            //Hit a Crate
            crate.Damage();            
        }

    }

}

매우간단하게 이런식으로

public Interface IDamageable{

    void Damage();
}

인터페이스를 추가하고


public class Enemy : MonoBehaviour , IDamageable{

    public void Damage();
}

public class Crate : MonoBehaviour , IDamageable{

    public void Damage();
}



이런식으로 변경할수있다.

public class Bullet : MonoBehaviour{

    private void OnTriggerEnter2D(Collider2D collider)
    {
       IDamageable damageable = collider.GetComponent<IDamageable>();

        if(damageable != null)
        {
            //Hit a Damageable Object
            damageable.Damage();
        }
    }

} 


원하는 어떤객체든지 IDamageable을 상속시키면 모두 사용가능하다




댓글 없음:

댓글 쓰기

git rejected error(feat. cherry-pick)

 문제 아무 생각 없이 pull을 받지않고 로컬에서 작업! 커밋, 푸시 진행을 해버렷다. push에선 remote와 다르니 당연히 pull을 진행해라고 하지만 로컬에서 작업한 내용을 백업하지 않고 진행하기에는 부담스럽다(로컬작업 유실 가능성) 해결하려...