Skip to content

Instantly share code, notes, and snippets.

@Islington036
Last active June 8, 2022 08:02
Show Gist options
  • Save Islington036/a6da23ed712649354b0bba8b963e049f to your computer and use it in GitHub Desktop.
Save Islington036/a6da23ed712649354b0bba8b963e049f to your computer and use it in GitHub Desktop.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public abstract class SingletonMonoBehaviour<T> : MonoBehaviour where T : MonoBehaviour
{
// 継承先で「破棄はできないか?」を指定
protected bool dontDestroyOnLoad = true;
// 継承したクラスの実体
private static T instance;
public static T Instance
{
get
{
// インスタンスがまだ無い場合
if (!instance)
{
Type t = typeof(T);
// 継承先のスクリプトをアタッチしているオブジェクトを検索
instance = (T)FindObjectOfType(t);
// 見つからなかった場合
if (!instance)
{
Debug.LogError(t + " がアタッチされているオブジェクトがありません");
}
}
return instance;
}
}
protected virtual void Awake()
{
// インスタンスが複数存在する場合は自身を破棄
if (this != Instance)
{
Destroy(this.gameObject);
return;
}
// 継承先で破棄不可能が指定された場合はシーン遷移時も破棄しない
if (dontDestroyOnLoad)
{
transform.parent = null;
DontDestroyOnLoad(this.gameObject);
}
}
protected virtual void OnDestroy()
{
// 破棄された場合は実体の削除を行う
if (this == Instance)
{
instance = null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment