반응형

하나의 객체만 존재해야 하는 싱글턴 패턴 게임 매니저 예제.

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
using UnityEngine.SceneManagement;
using UnityEngine.UI;
 
public class GameManager : MonoBehaviour
{
    public static GameManager instance;
 
    public bool isGameover = false;
    private Text scoreText; // Awake()에서 대입.
    public Text gameoverText;   // Editor - Inspector에서 대입. 시작할 때 비활성화 된
                                // 오브젝트이기 때문에 GameObject.Find()로 찾을 수 없다.
                                // 자식 오브젝트를 찾는 방식으로만 찾을 수 있다.
    
    public int marbleCount; // 마블 생성기에서 초기화.
 
    private void Awake()
    {
        if (instance == null)
        {
            instance = this;
 
            scoreText = GameObject.Find("ScoreText").GetComponent<Text>();
        }
        else
        {
            Debug.LogWarning("Game manager exists already.");
            Destroy(gameObject);
        }
    }
 
    // Update is called once per frame
    void Update()
    {
        if (!isGameover)
        {
            if (marbleCount <= 0)
            {
                isGameover = true;
                gameoverText.gameObject.SetActive(true);
            }
 
            scoreText.text = marbleCount + " marbles to go!!";            
        }
        else
        {
            if (Input.GetKeyDown(KeyCode.N))
            {
                isGameover = false;
                gameoverText.gameObject.SetActive(false);
                SceneManager.LoadScene(SceneManager.GetActiveScene().name);                
            }
        }
    }
}
cs

 

다른 스크립트에서 GameManager.instance.XXX 와 같은 방식으로 사용한다.

 

반응형
Posted by J-sean
: