본문 바로가기
개발/C#

유니티 C# 중복 생성 방지 간단 구현 DontDestroyOnLoad

by SPNK 2023. 1. 29.
반응형

코드 작성

using UnityEngine;

public class DuplicatePrevention : MonoBehaviour
{
    private static bool hasInstance = false;

    void Awake()
    {
        if (hasInstance)
        {
            // 이미 인스턴스가 존재하므로 이 인스턴스를 파괴합니다.
            Destroy(gameObject);
        }
        else
        {
            // 이 인스턴스가 유일하다는 것을 표시합니다.
            hasInstance = true;
            // 다른 씬으로 이동할 때 파괴되지 않도록 설정합니다.
            DontDestroyOnLoad(gameObject);
        }
    }
}
반응형

댓글