728x90
그림... 은 없고 가상함수와 오버라이드를 가장 쉽게 이해할 수 있는 예제-
몬스터를 가상함수로 만든다면! 입니다
이보다 적절한 예제가 있을까~ 물론 몬스터 역시 무언가로 상속 받고 그 상속 받은 모체를 PC 에도 적용
할 수 있고 하지만 이해를 위해서 다 버리고 몬스터와 보스만 가지고 어떻게 활용할 수 있는지 보시죠~
예제
// Monster.cs ------------------------------------------
using UnityEngine; // 유니티 엔진 안쓰면 지우면 됨
using System.Collections;
public class Monster : MonoBehaviour { // 유니티 엔진 안쓰면 MonoBehaviour 지우면 됨
public int m_nHp;
// Use this for initialization
virtual protected void Start () {
InitStat ();
}
virtual public void InitStat() {
m_nHp = 10;
}
public bool IsLive() {
return m_nHp > 0;
}
}
// Monster_Boss.cs --------------------------------------
using UnityEngine;
using System.Collections;
public class Monster_Boss : Monster {
// Use this for initialization
override protected void Start () {
base.Start (); // 일반 몬스터와 초기화는 같게
// 보스 등장 애니메이션!
}
// Monster_Boss 에서는 InitStat 을 호출 한 적 없지만 위의
// base.Start() 에서 InitStat 의 가상함수를 호출 함으로써 아래가 실행
override public void InitStat() {
m_nHp = 100;
}
// 여기엔 없지만 IsLive 가 있다고 보면 된다
}
// Stage.cs ----------------------------------------------
using UnityEngine;
using System.Collections;
public class Stage : MonoBehaviour {
protected ArrayList m_MobList; // Monster Object List
// Use this for initialization
void Start () {
m_MobList.Add (new Monster ());
m_MobList.Add (new Monster ());
m_MobList.Add (new Monster_Boss ());
}
// 몬스터 모두 죽었나 체크 (보스 포함)
protected bool CheckClear () {
for (int i=0; i<m_MobList.Count; i++) {
Monster tmp = (Monster)m_MobList [i]; // Monster_Boss 조차도 Monster 로 받을 수 있다
if(tmp.IsLive())
return false;
}
return true;
}
}
728x90
'프로그래밍 > C#' 카테고리의 다른 글
| C# long to Time (Day, Hour, Min) (0) | 2016.12.05 |
|---|---|
| C# 에서 ListView 항목 csv (엑셀) 로 저장 (0) | 2016.11.30 |
| ArrayList 초기화 방법들 (0) | 2016.09.23 |
| Close Button Event (0) | 2016.09.05 |
| RX vs2012 에서 설치 (0) | 2016.08.25 |
댓글