Skip to content

Instantly share code, notes, and snippets.

@valbeat
Last active January 21, 2016 03:36
Show Gist options
  • Save valbeat/fe683131bd25698c3646 to your computer and use it in GitHub Desktop.
Save valbeat/fe683131bd25698c3646 to your computer and use it in GitHub Desktop.
MonoBehaviourを継承したシングルトンの実装 ref: http://qiita.com/kajitack/items/4b0175755b0cc47d4f6e
using UnityEngine;
using System.Collections;
public class ScoreManager : SingletonMonoBehaviour<ScoreManager> {
public int score;
public void AddScore(int point) {
score += point;
}
}
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
/// <summary>
/// MonoBehaviourを継承したシングルトン
/// </summary>
public class SingletonMonoBehaviour<T> : MonoBehaviour where T : MonoBehaviour {
/// <summary>
/// インスタンス
/// </summary>
private static volatile T instance;
/// <summary>
/// 同期オブジェクト
/// </summary>
private static object syncObj = new object ();
/// <summary>
/// インスタンスのgetter/setter
/// </summary>
public static T Instance {
get {
// アプリ終了時に,再度インスタンスの呼び出しがある場合に,オブジェクトを生成することを防ぐ
if(applicationIsQuitting) {
return null;
}
// インスタンスがない場合に探す
if(instance == null) {
instance = FindObjectOfType<T>() as T;
// 複数のインスタンスがあった場合
if ( FindObjectsOfType<T>().Length > 1 ) {
return instance;
}
// Findで見つからなかった場合、新しくオブジェクトを生成
if (instance == null) {
// 同時にインスタンス生成を呼ばないためにlockする
lock (syncObj) {
GameObject singleton = new GameObject();
// シングルトンオブジェクトだと分かりやすいように名前を設定
singleton.name = typeof(T).ToString() + " (singleton)";
instance = singleton.AddComponent<T>();
// シーン変更時に破棄させない
DontDestroyOnLoad(singleton);
}
}
}
return instance;
}
// インスタンスをnull化するときに使うのでprivateに
private set {
instance = value;
}
}
/// <summary>
/// アプリが終了しているかどうか
/// </summary>
static bool applicationIsQuitting = false;
void OnApplicationQuit() {
applicationIsQuitting = true;
}
void OnDestroy () {
Instance = null;
}
// コンストラクタをprotectedにすることでインスタンスを生成出来なくする
protected SingletonMonoBehaviour () {}
}
using UnityEngine;
using System.Collections;
public class Test : MonoBehaviour {
void Start () {
Debug.Log(ScoreManager.Instance.score);
ScoreManager.Instance.AddScore(100);
Debug.Log(ScoreManager.Instance.score);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment