如何解决所以我试图将几个不同项目的列表排序到一个允许堆叠的库存槽列表中,并且每个槽只有 1 个带有计数的项目精灵
我暂时通过使用一堆列表将它们排序来完成此操作,但我知道这可以通过嵌套的 for 循环来完成。
public void AddToInventory(List<FoodResource> food)
{
for (int s = 0; s < slots.Length; s++)
{
for (int f = 0; f < food.Count; f++)
{
}
}
}
public class UISlot : MonoBehavIoUr
{
public FoodResource item;
public Image slotimage;
public Sprite icon;
public Text itemCount;
}
public class FoodResource : MonoBehavIoUr
{
public FoodResourceType foodType;
public Sprite sprite;
public float resourceValue;
public string uniqueName;
}
解决方法
当您传入一个食品项目列表时,这些食品项目可能已经或可能没有分配给 UISlot 的实例,因此最好将食品循环设为您的外循环。这样它会查看食物,然后查看匹配食物类型的所有插槽并插入它(如果存在),然后移动到下一个食物。例如:
for (int f = 0; f < foods.Count; f++) {
bool wasInserted = false;
for (int s = 0; s < slots.Length; s++) {
if (slots[s].item != null && slots[s].item.foodType == foods[f].foodType)
{
// Increase the number in your itemCount Text
wasInserted = true;
break; // It's inserted so move on to the next food item
}
}
// If the food wasn't inserted into any slot,find the first empty slot and insert it
if (!wasInserted) {
for (int s = 0; s < slots.Length; s++) {
if (slots[s].item == null) {
// Add the food to the inventory slot
break;
}
}
}
}
以上假设您的插槽和食物都已实例化。
使用 Linq 有一种更简单的方法,可能会更快。类似的东西:
using System.Linq;
/*
other stuff
*/
List<UISlot> slotsList = slots.ToList();
for (FoodResource foodResource in food) {
UISlot selectedSlot = slotsList.FirstOrDefault(s => s.item != null && s.item.foodType == foodResource.foodType);
if (selectedSlot != null) {
// Increment the itemCount
} else {
selectedSlot = slotsList.FirstOrDefault(s => s.item == null);
// Add item to empty slot
}
}
或者类似的东西。
在不知道如何/何时实例化项目的情况下,我认为这应该非常接近您的需要。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。