Skip to content

Instantly share code, notes, and snippets.

@HassakuTb
Created October 16, 2018 01:49
Show Gist options
  • Select an option

  • Save HassakuTb/bd3e2518553887d3f53c1f27bb2b015a to your computer and use it in GitHub Desktop.

Select an option

Save HassakuTb/bd3e2518553887d3f53c1f27bb2b015a to your computer and use it in GitHub Desktop.
MonoBehaviour that is accessed globally during scene is loaded.
using UnityEngine;
using UnityEngine.SceneManagement;
/// <summary>
/// 寿命がSceneのSingletonMonobehaviour
/// </summary>
/// <typeparam name="T"></typeparam>
public abstract class SceneSingletonMonoBeheviour<T> : MonoBehaviour
where T : SceneSingletonMonoBeheviour<T>{
/// <summary>
/// インスタンスを取得する
/// </summary>
public static T Instance { get; set; }
private string SceneName;
protected void Awake() {
if (Instance == null) {
Instance = this as T;
SceneName = gameObject.scene.name;
SceneManager.sceneUnloaded += SceneManager_sceneUnloaded;
}
else {
Destroy(gameObject);
}
}
private void SceneManager_sceneUnloaded(Scene scene) {
if (scene.name != SceneName) return;
SceneManager.sceneUnloaded -= SceneManager_sceneUnloaded;
Instance = null;
Debug.Log("UnLoad SceneSingleton : " + typeof(T).Name);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment