@ 기본적인 싱글톤 패턴
using UnityEngine;
public class GameManager : MonoBehaviour
{
// 싱글톤 인스턴스
public static GameManager instance { get; private set; }
// 게임 내에서 사용할 점수 변수
public int score;
// 유니티의 Awake() 메서드는 스크립트가 활성화될 때 가장 먼저 호출됩니다.
private void Awake()
{
// 만약 이미 인스턴스가 존재한다면, 이 오브젝트를 파괴합니다.
if (instance != null && instance != this)
{
Destroy(gameObject);
}
else
{
// 인스턴스가 존재하지 않는다면, 이 인스턴스를 설정하고 파괴되지 않도록 합니다.
instance = this;
DontDestroyOnLoad(gameObject);
}
}
// 점수를 추가하는 메서드
public void AddScore(int points)
{
score += points;
Debug.Log("Score: " + score);
}
}
기본적인 싱글톤 패턴
다른 스크립트에서 쓰기
using UnityEngine;
public class Player : MonoBehaviour
{
void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Coin"))
{
// GameManager의 인스턴스를 통해 점수를 추가합니다.
GameManager.instance.AddScore(10);
}
}
}
@ 미완성 싱글톤
public class MusicPlayer : Monobehaviour
{
void awake()
{
int numMusicPlayer = FindObjectsOfType<MusicPlayer>().Length;
if (numMusicPlayer > 1)
{
Destroy(gameObject);
}
else
{
DontDestroyOnLoad(gameObject);
}
}
}
싱글톤 패턴으로 개선한 코드:
public class MusicPlayer : MonoBehaviour
{
public static MusicPlayer instance { get; private set; }
void Awake()
{
if (instance != null && instance != this)
{
Destroy(gameObject);
}
else
{
instance = this;
DontDestroyOnLoad(gameObject);
}
}
}
유니티 그리드 시스템 적 움직이기 (0) | 2024.09.04 |
---|---|
유니티 편집모드에서 오브젝트 이름 바꾸기 (0) | 2024.09.04 |
유니티 하이어라키 오브젝트 부모 자식 옮기기 (0) | 2024.08.31 |
콜라이더, 트리거 충돌표 (0) | 2024.08.30 |
유니티 팁 여러개 오브젝트 정렬하기 (0) | 2024.08.29 |