Unity使用DontDestroyOnLoad的坑

使用DontDestroyOnLoad的坑

今天使用DontDestroyOnLoad();不销毁对象,当我的几个场景来回跳转的时候出现了问题,会重复生成这个不销毁的对象,可是我要的效果是无论怎么跳转就只存在一个这样的对象。
在这里插入图片描述

这是我写的代码

// ========================================================
// 描述:
// 作者:MeKey 
// 创建时间:2019-05-14 17:49:30
// 版 本:1.0
// ========================================================
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Dotdestroy : MonoBehaviour {
    private void Awake()
    {
        DontDestroyOnLoad(gameObject);             
    }
}

解决DontDestroyOnLoad的坑

更改脚本,挂到不销毁对象的物体上。而且这个脚本是个单利脚本。

/// ========================================================
// 描述:
// 作者:MeKey 
// 创建时间:2019-05-14 17:49:30
// 版 本:1.0
// ========================================================
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Dotdestroy : MonoBehaviour
{
    private static Dotdestroy instance;
    public static Dotdestroy Instance
    {
        get { return instance; }
    }
    private void Awake()
    {
        if (instance != null)
        {
            Destroy(gameObject);
            return;
        }
        instance = this;
        DontDestroyOnLoad(gameObject);
    }
}

这是我场景来回跳转几次之后的截图,只有唯一的一个对象。

在这里插入图片描述

微信公众号会定期推送一些资源
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_43109909/article/details/90378728
今日推荐