Unity/Unity 이슈
싱글톤 GameObject가 계속 늘어날 때
lipnus
2022. 3. 27. 00:23
반응형
Problem
싱글톤 오브젝트가 씬 생성시마다 계속 늘어난다.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
private static T instance;
public static T Instance
{
get {
if(instance == null)
{
GameObject obj;
obj = GameObject.Find(typeof(T).Name);
if (obj == null)
{
obj = new GameObject(typeof(T).Name);
instance = obj.AddComponent<T>();
}
else {
instance = obj.GetComponent<T>();
}
}
return instance;
}
}
public virtual void Awake()
{
DontDestroyOnLoad(gameObject);
}
}
Solution
Scene에 싱글톤에 의해서 생겨나는 코드를 미리 추가해서 넣어두면 계속 늘어나게 됨
싱글톤에 의해 생겨나야 될 객체를 미리 저렇게 GameObject로 넣어두면 싱글톤인데도
씬 생성할때마다 하나씩 계속 생김.
반응형