c# - Why is this function failing on the first iteration? - Stack Overflow

admin2025-04-17  1

I am making an inventory using unity and c#, where it will dynamically create text if the inventory slot has items in it. However, it always skips the first slot. When I first wrote the code it worked fine, but when I reopened unity it randomly stopped working. I cannot see any errors and the code does not break, but it has this weird behavior.

Here is the code:

// iterating i for every slot in inventory //

for (int i = 0; i < hotbar.children.Length; i++)
{
      if (inventory.items[i] != Resources.Load<Item>("Items/Empty"))
            {
                hotbar.children[i].GetComponent<Image>().sprite = inventory.items[i].sprite;
                if (GameObject.Find($"Hotbar ({i})") == null)
                {
                    textbox = new GameObject($"Hotbar ({i})", typeof(CanvasRenderer));
                    RectTransform tf = textbox.AddComponent(typeof(RectTransform)) as RectTransform;
                    tf.SetParent(hotbartextParent, true);
                    TextMeshProUGUI text = textbox.AddComponent(typeof(TextMeshProUGUI)) as TextMeshProUGUI;
                    text.SetText($"{inventory.itemCounts[i]}");
                    text.fontSize = 10;
                    text.color = new Color(0, 0, 0, 255);
                }
            }
}

For context, inventory.items[i] is the item in that slot (this all works fine I have checked).

I have just used a print command and I can confirm that it does make the textbox GameObject, it just doesn't show any of it in the engine?

Here are some images of the problem:

First item slot obviosuly there, but no text has been created to say there is 1 item in the slot

Now there is a second slot, it's made the text for the first slot

Close up

Third item now, still one textbox to the left

I just don't understand how this could be happening, as it works once more than one item is in your inventory, but never for the last one. Any ideas?

转载请注明原文地址:http://anycun.com/QandA/1744884416a88991.html