【发布时间】:2019-06-20 06:25:04
【问题描述】:
我目前无法打印数组的所有元素。我正在尝试使用嵌套的 for 循环来打印和编号所有元素,但我只能一遍又一遍地打印一个元素,这是我在游戏中单击的最后一个元素。
打印的前 7 个元素都相同,最后一个元素完全空白。
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PickUpItem : MonoBehaviour, IInteractable
{
public string DisplaySprite;
public string DisplayImage;
public int counter;
public int j;
public string[] ChoosenItems = new string[7];
private GameObject InventorySlots;
public void Interact(DisplayImage currentDisplay)
{
ItemPickUp();
}
void Start()
{
}
void Update()
{
}
void ItemPickUp()
{
InventorySlots = GameObject.Find("Slots");
counter = 0;
foreach (Transform slot in InventorySlots.transform)
{
if (slot.transform.GetChild(0).GetComponent<Image>().sprite.name == "empty_item")
{
slot.transform.GetChild(0).GetComponent<Image>().sprite =
Resources.Load<Sprite>("Inventory Items/" + DisplaySprite);
Destroy(gameObject);
break;
}
if (counter <= 7)
{
ChoosenItems[counter] = (gameObject.name);
counter++;
if (counter >= 7)
{
Debug.Log("You have choosen 8 itmes, would you like to continue or retry?");
for (j = 0; j <= 7; j++)
{
Debug.LogFormat("Element[{0}] = {1}", j, ChoosenItems[j]);
}
}
}
}
}
}
//http://csharp.net-informations.com/collection/list.html
【问题讨论】:
-
你试过调试你的代码吗?
-
我有,当我的计数器小于 7 时,它会在数组中添加一个项目并在计数器中添加 1。然后它一遍又一遍地将该项目添加到数组中,因为这是它被告知要做的事情。是否有另一种方法来执行我的功能而无需 for each 循环? for 循环的中断只允许它运行一次,所以我不能添加到其中的计数器或数组中。
标签: c# arrays unity3d nested-loops gameobject