ReplaceableMonoSingletonExample.cs 724 B

123456789101112131415161718192021222324252627282930313233
  1. using System.Collections;
  2. using UnityEngine;
  3. namespace QFramework.Example
  4. {
  5. public class ReplaceableMonoSingletonExample : MonoBehaviour
  6. {
  7. // Use this for initialization
  8. IEnumerator Start()
  9. {
  10. // 创建一个单例
  11. var instance = GameManager.Instance;
  12. // 强制创建一个实例
  13. new GameObject().AddComponent<GameManager>();
  14. // 等一帧,等待第二个 GameManager 把自己删除
  15. yield return new WaitForEndOfFrame();
  16. // 结果为 1
  17. Debug.Log(FindObjectsOfType<GameManager>().Length);
  18. // 最先创建的实例已经被删除
  19. Debug.Log(instance != FindObjectOfType<GameManager>());
  20. }
  21. public class GameManager : ReplaceableMonoSingleton<GameManager>
  22. {
  23. }
  24. }
  25. }