---
title: Singleton을 어떻게 사용하나요?
slug: world-sdk-guide-kr/singleton
docTags: 
createdAt: 2024-09-02T08:34:13.136Z
---

싱글턴은 프로그램 내에서 특정 클래스의 인스턴스가 하나만 존재하도록 보장하는 디자인 패턴입니다.

싱글턴 패턴은 클래스의 단일 전역 인스턴스를 제공하여, 논리 관리, 오디오, UI 및 월드 내 중앙 집중식 리소스와 같은 필요에 따라 다른 스크립트에서 쉽게 접근할 수 있도록 합니다.

ZEPETOScript에서 싱글턴을 다음과 같이 구현할 수 있습니다:

```typescript
private static _instance: ClassName = null;

public static get Instance(): ClassName {
	if (this._instance == null) {
		this._instance = GameObject.FindObjectOfType<ClassName>();
	}
	return this._instance;
}
```

:::hint{type="success"}
**👍 팁**

- 씬에 싱글턴 스크립트가 붙어 있는 GameObject가 이미 있다면, 이 형식을 사용할 수 있습니다.
- 없다면, GameObject를 생성하는 코드를 추가하세요.
  - 예: `new GameObject("ObjectName").AddComponent<ClassName>();`
:::

UI 관리를 위한 싱글턴을 예제로 구현해 보겠습니다:

1\) 씬에 UI > 텍스트 및 버튼을 추가하세요.

- "IncreaseScore" 버튼이 눌릴 때 점수를 증가시키는 로직을 설정하세요.
- "DecreaseScore" 버튼이 눌릴 때 점수를 감소시키는 로직을 설정하세요.

![](https://api.archbee.com/api/optimize/fCt3n1oCa8rgNJ8fw9I2N-WA4wOFac329w01mfJQcc3-20240904-102422.png)



2\) "ScoreManager"라는 스크립트를 생성하여 Singleton을 적용합니다.

- ScoreManager 스크립트는 점수를 증가/감소시키고 다른 스크립트에서 호출될 때 Text를 업데이트하는 역할을 합니다.

```typescript
import { ZepetoScriptBehaviour } from 'ZEPETO.Script';
import { GameObject } from 'UnityEngine';
import { Text } from 'UnityEngine.UI';
 
export default class ScoreManager extends ZepetoScriptBehaviour {
 
    // Singleton 선언
    private static _instance: ScoreManager = null;
 
    public static get Instance(): ScoreManager {
        if (this._instance == null) {
            this._instance = GameObject.FindObjectOfType<ScoreManager>();
        }
 
        return this._instance;
    }
 
    // 변수 선언
    public scoreText: Text;
    private _currentScore : number;
 
    Start() {   
        // 테스트를 위해 초기 점수를 0으로 설정
        this._currentScore = 0;
    }
 
    // 다른 스크립트에서 IncreaseScore를 호출할 수 있습니다.
    public IncreaseScore(amount: number) {
        this._currentScore += amount;
        this.scoreText.text = `점수 : ${this._currentScore}`;
    }
 
    // 다른 스크립트에서 DecreaseScore를 호출할 수 있습니다.
    public DecreaseScore(amount: number) {
        this._currentScore -= amount;
        this.scoreText.text = `점수 : ${this._currentScore}`;
    }
 
}

```



- 스크립트 설명
  - private static \_instance: 이것은 클래스 내의 비공식 정적 변수로, 처음에는 null로 설정됩니다.
  - public static get Instance: 이 정적 속성은 외부 코드가 이 클래스의 고유 인스턴스에 접근할 수 있는 방법을 제공합니다.
  - 확인 `if (this.\_instance == null)`. null인 경우, GameObject.FindObjectOfType\<>()를 사용하여 ClassName 유형의 구성 요소를 찾아 반환하고 이를 정적 변수에 할당합니다.



3\) 스크립트를 작성한 후, 검사기로 돌아가서 텍스트 컴포넌트를 연결합니다.

::Image[]{src="https://api.archbee.com/api/optimize/fCt3n1oCa8rgNJ8fw9I2N-ORrY57RIDdF3i0v1Rh0F9-20240904-102422.png" size="76" width="300" height="264" position="center" showCaption="false"}



4\) 다음으로, Singleton을 호출하는 방법을 보여주기 위해 "ScoreLogicSample"이라는 스크립트를 만듭니다. ScoreManager와 ScoreLogicSample이 같은 디렉토리에 있는지 확인하세요.

::Image[]{src="https://api.archbee.com/api/optimize/fCt3n1oCa8rgNJ8fw9I2N-J04ZZYJgBRuWFp5mI6tJ2-20240904-102422.png" size="62" width="247" height="146" position="center" showCaption="false"}

- 이와 같이 코드를 작성하세요:

```typescript
import { ZepetoScriptBehaviour } from 'ZEPETO.Script';
import { GameObject } from 'UnityEngine';
import { Text, Button } from 'UnityEngine.UI';
// Singleton 스크립트 가져오기
import ScoreManager from './ScoreManager';
 
export default class ScoreLogicSample extends ZepetoScriptBehaviour {
 
    public increaseScoreButton: Button;
    public decreaseScoreButton: Button;
 
    // ScoreManager 타입의 변수 선언
    private ScoreManager : ScoreManager;
 
    Start() {   
 
        // ScoreManager를 변수에 할당
        this.ScoreManager = GameObject.FindObjectOfType<ScoreManager>();
 
        this.increaseScoreButton.onClick.AddListener(()=> {
            // Singleton에 선언된 함수 호출
            this.ScoreManager.IncreaseScore(10);
        });
 
        this.decreaseScoreButton.onClick.AddListener(()=> {
            // Singleton에 선언된 함수 호출
            this.ScoreManager.DecreaseScore(10);
        });
    }
}
```



- 싱글톤 스크립트를 가져올 때 경로를 올바르게 지정하는 것이 중요합니다.
- 필요에 따라 자신의 스크립트에서 ScoreManager가 호출되는 부분을 조정할 수 있습니다.



5\) \[▶︎(재생)] 버튼을 눌러 테스트합니다.

- ScoreLogicSample에서 버튼을 클릭할 때 ScoreManager의 함수가 호출되는 것을 관찰해야 하며, 예상대로 작동합니다.

![](https://api.archbee.com/api/optimize/fCt3n1oCa8rgNJ8fw9I2N-nLqzRvwNUFM7TJ48BWbYl-20240904-102422.gif)

