ロバメモ - 素人のUnity覚書と奮闘記

素人のUnity覚書と奮闘記

シングルトンクラス

やりたいこと

シーンをまたいで変数値を保持するクラスを作りたい。

シングルトンクラスを作る

using UnityEngine;
using System.Collections;
 
public class Global : MonoBehaviour {
    static public Global instance;
  
    void Awake(){
        if (instance == null) {
            instance = this;
            DontDestroyOnLoad (this.gameObject);
        } else {
            Destroy (this.gameObject);
        }
    }

    public void MyMethod(){
        //TODO:処理
    }
}

ゲームオブジェクトにアタッチ

作成したシングルトンクラスをゲームオブジェクトにアタッチする

呼び出し方

クラス名.instance.変数またはメソッド

Global.instance.MyMethod();

以上。

albatrus.com