Singleton Pattern

JunDev·2025년 3월 11일

Unity

목록 보기
6/8

What is Singleton?

A Singleton is a design pattern used to ensure that only one instance of a class exists throughout the game. In Unity, this is often used for managing game managers, audio managers, input controllers, or any globally accessible system.

Why Use a Singleton?

  • Ensures there’s only one instance of a manager.
  • Provides global access to a class from anywhere in the game.
  • Helps prevent duplicate objects that could cause bugs.
using UnityEngine;

public class GameManager : MonoBehaviour
{
    public static GameManager instance; // Static reference to the single instance

    void Awake()
    {
        // Ensure only one instance exists
        if (instance == null)
        {
            instance = this;  // Set the instance to this object
            DontDestroyOnLoad(gameObject);  // Keep this object between scenes
        }
        else
        {
            Destroy(gameObject);  // Destroy duplicate instances
        }
    }
}

profile
Jun's Dev Journey

0개의 댓글