【问题标题】:Properly declare DontDestroyOnLoad正确声明 DontDestroyOnLoad
【发布时间】:2020-10-27 17:25:07
【问题描述】:

我在单个游戏对象上使用 DontDestroyOnLoad。当我切换到其他场景时,一切正常。但是当我回到我声明我的 DontDestroyOnLoad 游戏对象的初始场景时,问题出现了。它创建了我不需要的 gameObject 的另一个实例。我只需要这个运行的一个实例。我应该改变什么?

public static Script instance;

    void Awake () {
        DontDestroyOnLoad (gameObject);
        if (instance == null)
            instance = this;
        else
            Destroy (this);
    }

【问题讨论】:

    标签: c# unity3d


    【解决方案1】:

    您正在销毁您的 scipt 实例,而不是整个 GameObject。

    public static Script instance;
    
    void Awake () {
        if(instance == null)
        {
            instance = this;
            DontDestroyOnLoad (gameObject);        
        }
        else
            Destroy (gameObject);
    }
    

    【讨论】:

      猜你喜欢
      • 2012-05-30
      • 1970-01-01
      • 2022-11-18
      • 2023-03-16
      • 2018-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-19
      相关资源
      最近更新 更多