Skip to content

Instantly share code, notes, and snippets.

@IndieGameMaker
Created March 10, 2021 03:54
Show Gist options
  • Save IndieGameMaker/a3251e2c318a303ccad4e72c934b667c to your computer and use it in GitHub Desktop.
Save IndieGameMaker/a3251e2c318a303ccad4e72c934b667c to your computer and use it in GitHub Desktop.
[스크립트 8 5] GameManager - 싱글턴 구현
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameManager : MonoBehaviour
{
//몬스터가 출현할 위치를 저장할 List 타입 변수
public List<Transform> points = new List<Transform>();
//몬스터 프리팹을 연결할 변수
public GameObject monster;
//몬스터의 생성 간격
public float createTime = 3.0f;
//게임의 종료 여부를 저장할 멤버변수
private bool isGameOver;
//게임의 종료 여부를 저장할 프로퍼티
public bool IsGameOver
{
get{return isGameOver;}
set{
isGameOver = value;
if (isGameOver)
{
CancelInvoke("CreateMonster");
}
}
}
//싱글턴 인스턴스 선언
public static GameManager instance = null;
//스크립트가 실행되면 가장 먼저 호출되는 유니티 이벤트 함수
void Awake()
{
//instance가 할당되지 않았을 경우
if (instance == null)
{
instance = this;
}
//instance에 할당된 클래스의 인스턴스가 다를 경우 새로 생성된 클래스를 의미함
else if (instance != this)
{
Destroy(this.gameObject);
}
//다른 씬으로 넘어가더라도 삭제하지 않고 유지함
DontDestroyOnLoad(this.gameObject);
}
void Start()
{
//SpawnPointGroup 게임오브젝트의 Transform 컴포넌트 추출
Transform spawnPointGroup = GameObject.Find("SpawnPointGroup")?.transform;
//SpawnPointGroup 하위의 모든 차일드 게임오브젝트의 Transform 컴포넌트를 추출
foreach(Transform point in spawnPointGroup)
{
points.Add(point);
}
//일정한 시간 간격으로 함수를 호출
InvokeRepeating("CreateMonster", 2.0f, createTime);
}
void CreateMonster()
{
//몬스터의 불규칙한 생성 위치 산출
int idx = Random.Range(0, points.Count);
//몬스터 프리팹 생성
Instantiate(monster, points[idx].position, points[idx].rotation);
}
}
/*
//SpawnPointGroup 게임오브젝트 추출
GameObject spawnPointGroupObj = GameObject.Find("SpawnPointGroup");
if (spawnPointGroupObj != null)
{
//Transform 컴포넌트 추출
Transform spawnPointGroup = spawnPointGroupObj.GetComponent<Transform>();
//SpawnPointGroup 하위의 모든 차일드 게임오브젝트의 Transform 컴포넌트를 추출
points = spawnPointGroup.GetComponentsInChildren<Transform>();
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment