【问题标题】:Cannot output all elements of a gameObject array into the unity console无法将 gameObject 数组的所有元素输出到统一控制台
【发布时间】: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


【解决方案1】:

您声明您的 ChoosenItems = new string[7] 包含 7 个元素 ChoosenItems[0]ChoosenItems[6]。如您所见,这只有 7 项。因此,您永远不会有 8 个项目。尝试将其声明为 ChoosenItems = new string[8] 以使其包含 8 个项目。请参阅Mozilla Developer Docs 了解更多信息。

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 2013-05-13
    • 2011-03-24
    • 2019-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多