-
-
Save todorok1/b0dd69ad3a59112fff6adab23fdcc350 to your computer and use it in GitHub Desktop.
シングルトンでのFindAnyObjectByType()の使用例
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /// <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