问题描述
我暂时通过使用一堆列表将它们排序来完成此操作,但我知道这可以通过嵌套的 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
}
}
或者类似的东西。
在不知道如何/何时实例化项目的情况下,我认为这应该非常接近您的需要。