问题再现:
想让场景左侧目录列表“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