728x90
System.Acition(delegate)을 이용하여 이벤트를 발생시키는 방법에 대해서 알아볼 것이다. 이 방법은 이번에 공부하면서 알게 된 방법이다. 이 방법의 좋은 점은 단지 System.Action에 저장되어있는 함수를 실행하는 것을 목적으로 하기 때문에 Guard나 Player 스크립트가 사라져도 오류를 반환하지 않는다는 점이다.
1
2
3
4
5
6
7
8
9
|
public class Guard : MonoBehaviour
{
public static event System.Action OnGuardSpottedPlayer;
}
public class Player : MonoBehaviour
{
public static event System.Action OnReachEndOfLevel;
}
|
먼저 위의 코드를 Guard와 Player 스크립트에 추가시켜준다.
1
2
3
4
5
|
public class GameUI : MonoBehaviour
{
public GameObject gameWinUI;
public GameObject gameLoseUI;
bool gameIsOver;
|
GameUI스크립트를 만들어준다.
- gameWinUI - 게임을 승리했을 때 나오는 UI 정보를 저장하는 변수이다.
- gameLoseUI - 게임을 패배했을 때 나오는 UI 정보를 저장하는 변수이다.
- gameIsOver - 게임 승리했는지 패배했는지를 저장하는 변수이다.
1
2
3
4
5
|
void Start()
{
Guard.OnGuardSpottedPlayer += ShowGameLoseUI;
Player.OnReachEndOfLevel += ShowGameWinUI;
}
|
OnGuardSpottedPlayer에 ShowGameLoseUI 함수를 추가해주고, OnReachEndOfLevel에 ShowGameWinUI를 추가해준다.
1
2
3
4
5
6
7
8
9
10
|
void Update()
{
if (gameIsOver)
{
if (Input.GetKeyDown(KeyCode.Space))
{
SceneManager.LoadScene(0);
}
}
}
|
gameIsOver가 true가 되고 플레이어가 스페이스바를 누르게 되면 SceneManager.LoadScene(0)을 사용하여 게임을 다시 시작해준다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
void ShowGameWinUI()
{
OnGameOver(gameWinUI);
}
void ShowGameLoseUI()
{
OnGameOver(gameLoseUI);
}
void OnGameOver(GameObject gameObject)
{
gameObject.SetActive(true);
gameIsOver = true;
Guard.OnGuardSpottedPlayer -= ShowGameLoseUI;
Player.OnReachEndOfLevel -= ShowGameWinUI;
}
|
OnGameOver이 실행되면 플레이어가 승리를 했거나 가드가 플레이어를 검거했다는 의미이므로 게임을 종류시켜주고 다시 시작할 것을 대비하여 OnGuardSpottedPlayer에 ShowGameLoseUI를 제거해주고 마찬가지로 OnReachEndOfLevel 에 ShowGameWinUI를 제거해준다.
728x90
'Project > 도둑과 경호원' 카테고리의 다른 글
[도둑과 경호원] Unity: event 적용시키기 (0) | 2020.05.07 |
---|---|
[도둑과 경호원] Unity: Guard 플레이어 검거하기 (0) | 2020.05.05 |
[도둑과 경호원] Unity: Player 회전과 이동 (0) | 2020.05.04 |
[도둑과 경호원] Unity: Guard 기즈모 (0) | 2020.05.03 |
[도둑과 경호원] Unity: Guard 회전하기 (0) | 2020.05.02 |