I am making a oven baking system for my game and want to make a list with all the items I add into the oven, however when I iterate through each oven slot to check if it has a item child component attached to it, it only detects the first item I put into the oven, instead of returning a list with all the items I put into the oven.
void Update()
{
if (active)
{
CheckForRecipe();
}
}
void CheckForRecipe()
{
foreach (InventorySlot ovenSlots in ovenSlots)
{
itemsInOven.Add(ovenSlots[i].GetComponentInChildren<InventoryItem());
Debug.Log(itemsInOven);
}
}
try this…
using System.Collections.Generic; // Import this for List
private List<InventoryItem> itemsInOven = new List<InventoryItem>();
void Update()
{
if (active)
{
CheckForRecipe();
}
}
void CheckForRecipe()
{
// Clear the list before checking the oven slots to start with a fresh list
itemsInOven.Clear();
foreach (InventorySlot ovenSlot in ovenSlots)
{
// Check if there's an InventoryItem component attached to the slot
InventoryItem item = ovenSlot.GetComponentInChildren<InventoryItem>();
if (item != null)
{
itemsInOven.Add(item);
}
}
// Now you can print the list of items in the oven
foreach (InventoryItem item in itemsInOven)
{
Debug.Log(item.name);
}
}
Here, I just changed the clearing of the list.
using System.Collections.Generic; // Import this for List
private List<InventoryItem> itemsInOven = new List<InventoryItem>();
void Update()
{
if (active)
{
CheckForRecipe();
}
}
void CheckForRecipe()
{
// Create a temporary list to store the items in the oven
List<InventoryItem> tempItemsInOven = new List<InventoryItem>();
foreach (InventorySlot ovenSlot in ovenSlots)
{
// Check if there's an InventoryItem component attached to the slot
InventoryItem item = ovenSlot.GetComponentInChildren<InventoryItem>();
if (item != null)
{
tempItemsInOven.Add(item);
}
}
// Assign the temporary list to itemsInOven after all slots have been checked
itemsInOven = tempItemsInOven;
// Now you can print the list of items in the oven
foreach (InventoryItem item in itemsInOven)
{
Debug.Log(item.name);
}
}
Thanks for your reply, I have added the code however it seems to only work when I simultaneously add the items, but the gameplay would be to add the items individually.
Thanks heaps, for all your help, this updated code is just what I needed to get this oven script working.