Skip to content

Instantly share code, notes, and snippets.

@todorok1
Last active January 21, 2026 03:08
Show Gist options
  • Select an option

  • Save todorok1/b0dd69ad3a59112fff6adab23fdcc350 to your computer and use it in GitHub Desktop.

Select an option

Save todorok1/b0dd69ad3a59112fff6adab23fdcc350 to your computer and use it in GitHub Desktop.
シングルトンでのFindAnyObjectByType()の使用例
/// <summary>
/// フラグを管理するクラスです。
/// </summary>
public class FlagManager : MonoBehaviour
{
/// <summary>
/// このクラスのインスタンスです。
/// </summary>
private static FlagManager _instance;
/// <summary>
/// このクラスのインスタンスです。
/// </summary>
public static FlagManager Instance
{
get
{
// staticなインスタンスがなければ、シーン内にあるものを検索します。
if (_instance == null)
{
_instance = FindAnyObjectByType<FlagManager>();
// シーン内になければ作成します。
if (_instance == null)
{
GameObject singletonObject = new();
_instance = singletonObject.AddComponent<FlagManager>();
singletonObject.name = typeof(FlagManager).ToString() + " (Singleton)";
DontDestroyOnLoad(singletonObject);
}
}
return _instance;
}
}
private void Awake()
{
// Awake()のタイミングでstaticのフィールドを確認し、
// 参照がなければ自身をアサイン、あれば自身を削除します。
if (_instance == null)
{
_instance = this;
DontDestroyOnLoad(gameObject);
}
else if (_instance != this)
{
Destroy(gameObject);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment