이 글은
https://www.inflearn.com/course/유니티-게임-프로그래밍-에센스
강의를 요약한 강의노트 입니다.
유니티를 처음 접하시는 분들이거나 좀 더 기반을 다지고 싶으신 분들에게 👍강력하게 추천합니다.
디자인 패턴 : 프로그래머들 사이에서 공유되는 어떠한 코드를 작성하는 방향을 말한다.
싱글톤 : 다지안 패턴 중 하나로 기본적으로 게임이나 메모리 상에 단 하나만 존재하고 언제 어디서든 접근 가능한 오브젝트를 만들 때 사용하는 패턴이다.
사용 예시) 다수의 몬스터를 관리하는 몬스터매니저는 단 하나만 존재하면 된다.
사용 방법 : 언제 어디서든 접근이 가능하고 단 하나만 존재할 수 있도록 static으로 선언한다.
this : 자기 자신을 가리키는 키워드
FindObjectOfType<>() : 씬상에 존재하는 모든 오브젝트를 뒤져서
<>안에 해당하는 오브젝트를 찾아 리턴한다.
Destroy(gameobject) : gameobject를 씬상에서 제거한다.
AddComponent<>() : 오브젝트에 <>에 해당하는 컴포넌트 넣기
코드 설명
- 하나만 존재해야 할 자기 자신을 가리킬 정적 변수 instance를 선언한다.
static ScoreManager1 instance;
- instance가 하나만 존재하고 언제 어디서든 접근이 가능할 수 있도록 정적함수를 선언한다.
public static ScoreManager1 GetInstance() { if (instance == null) // instance가 비어있다면 수행 { instance = FindObjectOfType<ScoreManager1>(); //FindObjectOfType를 통해 ScoreManager1의 오브젝트를 찾아 리턴한다. if (instance == null) // 씬상에 해당 오브젝트가 존재하지 않는 경우 { // ScoreManager1의 오브젝트를 생성한다. // 이름 넣기 GameObject container = new GameObject("ScoreManager1"); // container에 ScoreManager1컴포넌트를 넣고 instance에 넣기 instance = container.AddComponent<ScoreManager1>(); } } return instance; // 리턴 }
3. 만약 ScoreManager1 오브젝트가 여러개 존재한다면 기존 하나를 제외한 나머지를 제거한다.void Start() { if (instance != null) { if (instance != this) { Destroy(gameObject); } } }
- 생성
Awake를 통해 게임 실행전 초기화하여 생성한다.void Awake() { GetInstance(); }
- 외부함수에서의 접근
ScoreManager1.GetInstance().AddScore(5);
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ScoreManager1 : MonoBehaviour
{
public static ScoreManager1 GetInstance()
{
if (instance == null)
{
instance = FindObjectOfType<ScoreManager1>();
if (instance == null)
{
GameObject container = new GameObject("ScoreManager1");
instance = container.AddComponent<ScoreManager1>();
}
}
return instance;
}
static ScoreManager1 instance;
int score = 0;
void Start()
{
if (instance != null)
{
if (instance != this)
{
Destroy(gameObject);
}
}
}
public int GetScore()
{
return score;
}
public void AddScore(int newScore)
{
score += newScore;
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ScoreAdder : MonoBehaviour
{
void Awake()
{
Debug.Log("Start Score " + ScoreManager1.GetInstance());
}
void Update()
{
if (Input.GetMouseButtonDown(0))
{
ScoreManager1.GetInstance().AddScore(5); // static공간에 instance란 ScoreManager1이 생성되어 이를 사용해 접근할 수 있다.
Debug.Log(ScoreManager1.GetInstance().GetScore());
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ScoreSub : MonoBehaviour
{
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(1))
{
ScoreManager1.GetInstance().AddScore(-2);
Debug.Log(ScoreManager1.GetInstance().GetScore());
}
}
}