Skip to content

Instantly share code, notes, and snippets.

@HassakuTb
Created June 29, 2016 03:27
Show Gist options
  • Save HassakuTb/608a518b5d8c45e75d7135dacdac1cbf to your computer and use it in GitHub Desktop.
Save HassakuTb/608a518b5d8c45e75d7135dacdac1cbf to your computer and use it in GitHub Desktop.
SingletonなScriptableObject基底クラス
/**
NYSL Version 0.9982 (en) (Unofficial)
----------------------------------------
A. This software is "Everyone'sWare". It means:
Anybody who has this software can use it as if he/she is
the author.
A-1. Freeware. No fee is required.
A-2. You can freely redistribute this software.
A-3. You can freely modify this software. And the source
may be used in any software with no limitation.
A-4. When you release a modified version to public, you
must publish it with your name.
B. The author is not responsible for any kind of damages or loss
while using or misusing this software, which is distributed
"AS IS". No warranty of any kind is expressed or implied.
You use AT YOUR OWN RISK.
C. Copyrighted to Hassaku
D. Above three clauses are applied both to source and binary
form of this software.
*/
using UnityEngine;
using UnityEngine.Assertions;
public class SingletonScriptableObject<T> : ScriptableObject where T : SingletonScriptableObject<T>{
private static T _instance { get; set; }
/// <summary>
/// 唯一のインスタンスを取得する
/// 初回呼び出しは低速なので注意
/// </summary>
public static T Instance {
get {
if (_instance == null) {
var objects = Resources.FindObjectsOfTypeAll<T>();
Assert.IsTrue(objects.Length <= 1);
if (objects.Length == 1) {
_instance = objects[0];
}
else {
_instance = ScriptableObject.CreateInstance<T>();
}
}
return _instance;
}
}
}
@HassakuTb
Copy link
Author

ReourcesにAssetが1つあればそれをロード
1つも無ければインスタンスを作成
複数あればAssert

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment