统一中的单例模式删除重复对象

发布于 2025-02-10 00:57:48 字数 509 浏览 1 评论 0原文

gamemanager.cs


private void Awake()
    {
        //check if instance is null, if null then create 
        if (instance == null) {
            //refers to the GameManager class
            instance = this;
            //dont destroy gamemanger game object when loading new scene
            DontDestroyOnLoad(gameObject);
        } else {

            Destroy(gameObject);
        }
    }  

为什么使用单身模式需要销毁(gameObject)?为什么首先要创建第二个实例?

GameManager.cs


private void Awake()
    {
        //check if instance is null, if null then create 
        if (instance == null) {
            //refers to the GameManager class
            instance = this;
            //dont destroy gamemanger game object when loading new scene
            DontDestroyOnLoad(gameObject);
        } else {

            Destroy(gameObject);
        }
    }  

Why is Destroy(gameObject) necessary with a singleton pattern? Why would a second instance be created in the first place?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

初与友歌 2025-02-17 00:57:48

它可以通过不同的原因创建。例如:

  • 如果对象使用此脚本在场景中再次加载场景,则
  • 使用此脚本实例化对象
  • ,也许尝试手动将组件添加到对象中(这是完全合法的,可以调用gameBoct.Addcompont&lt ; myaweSometype>()),

因此您无法确定对象不会重复,因此您必须确保只有第一个创建的实例才能活着

It can be created by different reasons. For example:

  • Loading the scene again in case of an object with this script is in the scene
  • Instantiating an object with this script attached
  • Perhaps some attempt to manually add a component to an object (this is completely legal to call gameObject.AddComponent<MyAwesomeType>())

So as you cannot be sure that object will not be duplicated, you have to be sure that only the first created instance stays alive

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文