admin管理员组

文章数量:1130349

退出游戏时报错: Some objects were not cleaned up when closing the scene. (Did you spawn new GameObjects from OnDestroy?)

原因

正常情况下,在OnDisable或者OnDestroy生命周期中实例化GameObject是可以的。但是退出游戏时也会调用OnDisable或者OnDestroy,就造成了退出游戏时实例化GameObject

解决

思路很简单,就是在OnDisable或者OnDestroy生命周期中判断目前是否是正在退出游戏

按照Unity官方提供的生命周期执行顺序

会发现最后一阶段生命周期函数执行顺序为OnApplicationQuit -> OnDisable -> OnDestroy

所以第一种解决方法如下

using UnityEngine;

public class Example : MonoBehaviour
{
    private bool _isQuitting = false;

    private void OnApplicationQuit()
    {
      _isQuitting = true;
    }

    private void OnDisable()
    {
      if(_is

退出游戏时报错: Some objects were not cleaned up when closing the scene. (Did you spawn new GameObjects from OnDestroy?)

原因

正常情况下,在OnDisable或者OnDestroy生命周期中实例化GameObject是可以的。但是退出游戏时也会调用OnDisable或者OnDestroy,就造成了退出游戏时实例化GameObject

解决

思路很简单,就是在OnDisable或者OnDestroy生命周期中判断目前是否是正在退出游戏

按照Unity官方提供的生命周期执行顺序

会发现最后一阶段生命周期函数执行顺序为OnApplicationQuit -> OnDisable -> OnDestroy

所以第一种解决方法如下

using UnityEngine;

public class Example : MonoBehaviour
{
    private bool _isQuitting = false;

    private void OnApplicationQuit()
    {
      _isQuitting = true;
    }

    private void OnDisable()
    {
      if(_is

本文标签: unity踩坑一