091

[C#] Unity 속 C# script(9) : GameManager 본문

Programming Language/C#

[C#] Unity 속 C# script(9) : GameManager

공구일 2024. 12. 11. 03:16
728x90

01. GameManager

- Unity에서 게임의 전반적인 흐름과 상태를 관리하는 중심 역할을 하는 스크립트를 의미, 개발자가 필요에 따라 만들어 사용하는 관습적인 디자인 패턴 -> 게임 상태나 공통 데이터 등을 중앙에서 조율하고 관리함

-> 코인 수를 세는 메서드를 GameManger만들어 붙이고 공에서 실행시켜서 세기

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//using UnityEngine.SceneManagement;

public class gameManagerS : MonoBehaviour
{
    private int ycount = 0;
    public void CountMethod(){
        ycount++;
        Debug.Log("먹은 코인수는"+ycount);
    }
    public void TotCount(){
    	Debug.Log("수고했습니다. 최종 "+ycount+"개 먹음");
    }
}

- GameManager 객체(빈 객체)에 해당 스크립트를 부착시켜줌

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//using UnityEngine.SceneManagement;

public class ball_ggi : MonoBehaviour
{
    GameObject GM;
    void OnTriggerEnter(Collider col){
        if(col.tag == "YCoin") 
        {
            Destroy(col.gameObject); //코인이 사라짐
            GM = GameObject.Find("GameManager");
            GM.GetComponent<gameManagerS>().CountMethod();
            GM.GetComponent<gameManagerS>().TotCount();
        }
    }
}

- 공에 붙여준 스크립트로 GameObject GM(파견객체)을 만들고 게임매니저 객체를 집어넣은 뒤 요소에서 스크립트를 가져와 미리 만들어둔 두가지의 메서드를 사용함

 

02. Text UI

-> ycount의 값을 실시간으로 화면에 표시할 수 있는 코드를 추가함

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//using UnityEngine.SceneManagement;

public class gameManagerS : MonoBehaviour
{
    private int ycount = 0;
    private int gcount = 0;
    public Text coinCount;
    public Text remCount;
    public void CountMethod(){
        ycount++;
        Debug.Log("먹은 코인수는"+ycount);
        coinCount.text = "사라진 코인수 " + ycount.ToString();
        remCount.text = "남은 코인수 " + (6-ycount).ToString();
    }
    public void TotCount(){
    	Debug.Log("수고했습니다. 최종 "+ycount+"개 먹음");
    }
    public void GCount(){
    	gcount++;
        Debug.Log("연두색 코인을 먹었습니다.");
        remCount.text = "사라진 연두색 코인수 " + gcount.ToString();
    }
}

- Text coinCount로 만들고 인스펙터창에서(public)에서 만든 Text를 집어 넣어줌, ycount.ToString()은 원래 명시적 형변환 하지 않아도 괜찮지만 가독성을 위해 써줌(참고로, DateTime, Vector3 등의 복잡한 자료형을 다룰 때는 꼭 작성해줘야함) 

* Text를 만드는 방법은 GameObject -> UI -> Text

 

 

더보기

* 일부 출처 - 고수정, ”게임프로그래밍 ”, 인덕대학교

728x90