Foreach loop is sending Object reference is not set to an instance of an object

Hello, I am making a crafting system and want to add all of the items names that are in the grid to be added to a list so I can check what items are in there, however when iterating through each grid using a foreach loop it gives a reference error.

private void CheckItemsInOven()
{
    itemsInOven.Clear();
    foreach (InventorySlot ovenSlot in ovenSlots)
    {
        if (ovenSlot.GetComponentInChildren<InventoryItem>() != null)
        {
            string item = ovenSlot.GetComponentInChildren<InventoryItem>().item.itemName;
    
            itemsInOven.Add(item);
    
            if(CheckRecipe(itemsInOven))
            {
                CookRecipe(true);
            }
            else
            {
                CookRecipe(false);
            }
        }
    }
}

this error only started occurring after I added .item.itemName, if I were to remove that and change list to type InventoryItem it works fine. any help would be appreciated.

Could you try rewriting your code a bit and add some debugging?
The problem must be with the item member of the InventorySlot class.

Try this:

foreach (InventorySlot ovenSlot in ovenSlots)
{
    var inventoryItem = ovenSlot.GetComponentInChildren<InventoryItem>();
    
    // Debugging - You can remove this if-block when you're done debugging
    if (inventoryItem != null && inventoryItem.item == null)
    {
        Debug.Log("Warning: inventoryItem.item == null", inventoryItem);
        continue; // Skips to the next ovenSlot in the foreach loop
    }

    if (inventoryItem != null && inventoryItem.item != null)
    {
        // NOTE: Variable "item" renamed "itemName" for the sake of readability
        string itemName = inventoryItem.item.itemName;

        itemsInOven.Add(itemName);

        if(CheckRecipe(itemsInOven))
        {
            CookRecipe(true);
        }
        else
        {
            CookRecipe(false);
        }
    }
}

Just in case you haven’t used it before:
The 2nd parameter of the Debug.Log() method is the context.
When it logs it, you can click on the log entry and the scene hierarchy will focus on the gameobject that the context is referencing.