How can I populate the first null of an array and only the first?

I am wanting to cycle through the array, find the first element where the item name field is null, and populate that element.


Code:

    public void AddItem(Item item)
    {
        for (int i = 0; i < inventorySize; i++)
        {
            if (inventoryItems*.itemName == null)*

{
inventoryItems = item;
break;
}
}
}
----------
So far it works well enough and will populate the array just fine but only if all of the name fields are null.
----------
Am I even on the right track?

Try it this way.

public void AddItem(Item item)
{
	 for (int i = 0; i < inventoryItems.Length; i++)
	 {
		 if (inventoryItems *== null)*
  •   {*
    

_ inventoryItems = item;_
* break;*
* }*
* }*
}

You first say find the first itemName null and populate, you are already doing that… later you say that it works, but it will populate the array only if all of the names are null, what exactly are you trying to achieve?


I think you need to add a better description of the actual behaviour that you want your method to have and maybe look into the LIst<> type which lets you easily Add items or Remove them (automatically shortening the List size).

Not sure why it doesn’t work, but my solution, though a little ugly, would be to use a ticker variable. This would ensure that only the first time that the name is null, the element is set. Something like this:

public void AddItem(Item item)
     {  
         bool ticker = true;
         for (int i = 0; i < inventorySize; i++)
         {
             if (ticker && inventoryItems*.itemName == null)*

{
inventoryItems = item;
ticker = false;
}
}
}

Your code is correct. It will loop trough your inventoryItems, the first one that has a itemName field that is null will get the object. Then the loop will break. I think you have to explain a bit more about the problem you are having. Either attach the visual studio debugger to your code and step trough it to seeing what is going, or Put some debugging logs into the code to see what is going on.

What happens if you add these debug statements to your code? Does it help you understand the problem? If not share the output with us and it should be easier to find what is going wrong.

Also are you sure your inventorySize is correct? Is it a list or an array? I would recommend setting the inventorySize in that function to either inventoryItems.Length or inventoryItems*.Count depending if you have an array or list.*
public void AddItem(Item item)
{
int inventorySize = inventoryItems.Length; (or .Count if it is an array)
Debug.Log(“Calling AddItem”);
for (int i = 0; i < inventorySize; i++)
{
Debug.Log("ItemNr: {i} name: {inventoryItems*.itemName}");*_ <em>_if (inventoryItems*.itemName == null)*_</em> <em>_*{*_</em> <em><em>_inventoryItems *= item;*_</em></em> <em><em>_*Debug.Log(“ItemNr: {i} assigned the name {item}”);*
break;
}
}
}