首页 > 解决方案 > 如何一一打印数组的所有元素?

问题描述

我需要一些编程方面的帮助。我有一个包含 int 数字的列表,我需要将它们转换为字符串数组并逐个打印所有元素。我的代码都在 Update 函数中,如果我在 Update 函数中打印一个数组,它将运行很多次并打印很多值。所以我只需要以某种方式调用一个函数,该函数在存储一个值后打印一个数组,或者一次打印存储在数组中的所有值。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PrintData: MonoBehaviour
{
    float tmp = 0;

    public List<int> CheckKeyPress = new List<int>(); //this is list that will 
    //have only 0 if user pressed key Z and only 1 if user presses key X. It will 
    //store in list 20 values (of 0 or 1).

    void Update()
    {
        // Here I check what did the user press after they hear some sound.
        tmp += Time.deltaTime;

        if ((Input.GetKey(KeyCode.Z)))
        {
            if (tmp >= 1) //I do this following someone's advice. Otherwise all 
        //this code wouldn't work in update function
            {
                CheckKeyPress.Add(0);
            }

            tmp = 0;
        }
        else if (Input.GetKey(KeyCode.X))
        {
            if (tmp >= 1) 
            {
                CheckKeyPress.Add(1);
            }

            tmp = 0;
        }

       //Here I want to make the array of strings from the list called
       //"CheckKeyPress ",and print all elements one by one. 

    }
}

我想一个一个地打印数组的元素(在它们存储在列表中时),或者在列表获得所有 20 个元素之后打印它们。

标签: c#unity3d

解决方案


您可以使用string.Join()来连接您的所有项目List<int>,并通过指定的分隔符将它们分开:

Debug.Log(string.Join(",", CheckKeyPress.ConvertAll(x => x.ToString()).ToArray()));

推荐阅读