DontDestroyOnLoad方法踩坑——场景A某物体用DontDestroyOnLoad,从场景B返回场景A时,会生成两个此物体

问题再现:

                  想让场景左侧目录列表“Canvas_Titles”,在下个场景中仍然显示,就在它的脚本里加了DontDestroyOnLoad方法


using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DontDestroy : MonoBehaviour
{

     void Awake()

        {
        DontDestroyOnLoad(this.gameObject);

        }

}

在这里插入图片描述
                  但从第二个场景返回时,出现了两个目录列表Canvas_Titles
在这里插入图片描述

解决方法:

                  保留最早的,删掉后来生成的

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DontDestroy : MonoBehaviour
{

     void Awake()

        {
        DontDestroyOnLoad(this.gameObject);

        }
    void OnEnable()
    {
        GameObject[] canvasTitlsArray = GameObject.FindGameObjectsWithTag("CanvasTitles");
        if (canvasTitlsArray.Length > 1)
        {
            for (int i = 0; i < canvasTitlsArray.Length; i++)
            {
                if (i == 0)//canvasTitlsArray.Length[0]是最早的
                {
                    continue;
                }
                else
                {
                    Destroy(canvasTitlsArray[i]);
                }
            }
        }
    }
}
补充:

此处找物体,最好用GameObject.FindGameObjectsWithTag

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值