LoginSignup
15

More than 5 years have passed since last update.

Unityでシングルトン

Posted at

シングルトンとは?

そのクラスのインスタンスが必ず1つであることを保証するデザインパターン

"○○○Manager"などのクラスを作成し、データの保存・管理に利用されることが多い

  • 呼び出しが楽
  • メンテナンスが楽

実例

Unityチュートリアルのサバイバルシューターのスコアをシングルトンで管理する。

シングルトンクラスの作成

EventManager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EventManager : MonoBehaviour {

    private static EventManager mInstance;
    private int num = 0;

    public static EventManager Instance {
        get {
            if( mInstance == null ) {
                GameObject obj = new GameObject("EventManager");
                mInstance = obj.AddComponent<EventManager>();
            }
            return mInstance;
        }
        set {

        }
    }

    public void setScore( int n ) {
        this.num = n;
    }
    public int getScore() {
        return this.num;
    }

}

使ってみる

スコアが更新されたら新しいスコアをsetする

EnemyHealth.cs
EventManager eventManager;

void Awake ()
{
    eventManager = EventManager.Instance;
}

public void StartSinking ()
{
    var currentScore = eventManager.getScore();
    currentScore += scoreValue;
    eventManager.setScore(currentScore);
}

ScoreManagerの中でスコアをgetする

ScoreManager.cs
EventManager eventManager;

void Awake ()
{
    eventManager = EventManager.Instance;
}

void Update()
{
    score = eventManager.getScore();
}

参考
Unityでよく使うデザインパターン

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15