c# - 如何销毁引用数组的对象而不将它们从 Unity 2D 中的数组中删除?
问题描述
我最近开始创建游戏,但是当我尝试破坏场景中的对象时,它们也会从列表中删除。这是代码:
List<GameObject> objects = new List<GameObject>();
int x = 650;
// Here I try to destroy objects
foreach(Transform obj in transform) {
Destroy(obj.gameObject);
}
// Here I instantiate all objects from the array
for(int i = 0;i < objects.Count;i++) {
if(objects.Count == 3) {
GameObject prefab_copy = (GameObject)Instantiate(objects[i], new Vector2(x, 1150), Quaternion.identity );
prefab_copy.GetComponent<Image>().enabled = true;
prefab_copy.transform.SetParent(parentobj.transform);
x = x + 100;
}
}
cleanItemList = true;
解决方案
将空值保存在列表中然后尝试从中进行实例化是危险的,请在销毁游戏对象后立即从列表中删除,您不能在播放模式下保留对已删除游戏对象的引用。
我的建可以理解你需要学习OBJECT POOLING的问题。它将帮助你重用相同的对象并提高性能。
推荐阅读
- python - 如何在python selenium中找到元素的标题
- rabbitmq - RabbitMQ Camel Consumer - 消费一条消息
- linux - 在linux目录中的所有文件中运行脚本
- html - 当前课堂主题
- javascript - 在场景中的 Mapbox-gl 中“单击”时不会触发“mouseDown”事件
- typescript - 定义对象键但推断值
- javascript - 在 Google 表格中的表格顶部添加 fow
- html - 将宽度设置为 100% 以上后,div 水平向右移动
- javascript - 仅向弹出图像添加文本
- .htaccess - 尝试使用 .htaccess 进行 www 和 https 重定向