现在,我正在编写一个函数,该函数将清理 UI 中的列表 (ProjectsUpdate())(图 1)并将预制件中的新插槽加载到其中,但我面临的事实是,并非所有列表元素都是已删除。我开始一步步调试,发现当我删除列表的第一个元素时,再次输入foreach就会被跳过。如何确保列表正常清理?我附上了脚本和拓扑(图 1)。
using UnityEngine;
using System.IO;
using UnityEngine.UI;
using TMPro;
using System.Linq;
public class ProjectViewManager : MonoBehaviour
{
[SerializeField] private Transform table;
[SerializeField] private GameObject slotTemp;
public void ProjectsUpdate()
{
print(table.childCount);
if (table.childCount > 0)
{
foreach (Transform child in table) DestroyImmediate(child.gameObject);
}
var list = System.IO.Directory.GetFiles(Application.persistentDataPath);
foreach (var file in list.ToList()) OpenJson(file);
}
public void SetTemp(string name,int cost,int duration)
{
GameObject temp = Instantiate(slotTemp,table);
temp.transform.Find("name").GetComponent<TextMeshProUGUI>().text = name;
temp.transform.Find("cost").GetComponent<TextMeshProUGUI>().text = "cost:"+cost.ToString();
temp.transform.Find("duration").GetComponent<TextMeshProUGUI>().text = "duration:"+duration.ToString();
}
private void Start()
{
ProjectsUpdate();
}
public void OpenJson(string name)
{
string dataToLoad = "";
string fullPath = Path.Combine(Application.persistentDataPath, name);
FileStream stream = new FileStream(fullPath, FileMode.Open);
StreamReader reader = new StreamReader(stream);
dataToLoad = reader.ReadToEnd();
ProjData data = JsonUtility.FromJson<ProjData>(dataToLoad);
SetTemp(data.projName, data.cost, data.duration);
reader.Close();
}
}