「Unity/Csharp/シングルトン」の版間の差分
提供: 初心者エンジニアの簡易メモ
(→通常シングルトン) |
|||
行4: | 行4: | ||
private SampleManager () { | private SampleManager () { | ||
} | } | ||
− | public static | + | public static SampleManager Instance { |
get { | get { | ||
if( mInstance == null ) mInstance = new SampleManager(); | if( mInstance == null ) mInstance = new SampleManager(); |
2017年10月22日 (日) 18:43時点における版
通常シングルトン
public class SampleManager { private static SampleManager mInstance; private SampleManager () { } public static SampleManager Instance { get { if( mInstance == null ) mInstance = new SampleManager(); return mInstance; } } }
MonoBehaviourを使ったシングルトン
using System.Collections; using System.Collections.Generic; using UnityEngine; public class SampleManager : MonoBehaviour { private static SampleManager mInstance; public int x = 1; private SampleManager () { } public static SampleManager Instance { get { if (mInstance == null) { GameObject go = new GameObject("SampleManager"); mInstance = go.AddComponent<SampleManager>(); } return mInstance; } } void Start () { } void Update () { } }
使用方法
SampleManager manager = SampleManager.Instance; Debug.Log("x=" + manager.x);