将文本文件中的值添加到二维数组 c#

Adding values from text file to 2D Array c#

已编辑--- 我在 foreach 循环中向二维数组添加值时遇到问题。 Hari 指出我需要在循环之前声明 i = 0 和我的数组,并且我已经向后分配了值。 (谢谢)。 但是,我尝试添加一个最终强度数组,Debug.Log i 的值和控制台读取 "System.Single[]" 而不是单个值。知道这是为什么吗? 谢谢!!

这是我的代码:

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

//[Serializable]
public class MultiArrayList2 : MonoBehaviour {

public TextAsset datafile;
private int i;
private float[,] coordinates;
private float[] intensity;

// Use this for initialization
void Start() {

    string[] dataLines = datafile.text.Split ('\n');
    string[] lineValues;
    //print (dataLines.Length);
    i=0;

    float[,] coordinates = new float[6853, 3];  
    float[] intensity = new float[6853];
    foreach (string line in dataLines) {

        lineValues = line.Split (' ');
        float coordinateX = float.Parse (lineValues [0]);
        float coordinateY = float.Parse (lineValues [1]);
        float coordinateZ = float.Parse (lineValues [2]);
        float intens = float.Parse (lineValues [3]);

        coordinates [i, 0] = coordinateX;
        coordinates [i, 1] = coordinateY;
        coordinates [i, 2] = coordinateZ;

        intensity [i] = intens;

        Debug.Log (intensity);

        i++;        

    }

}

}

你没有给数组元素分配任何东西,当你第一次让你的数组元素不包含任何值然后你将它们分配给 coordinateX 它应该是相反的,

 coordinates [i, 0] = coordinateX;

几点。

  1. 你还没有初始化i,在循环之前初始化这个变量(foreach)
  2. coordinates 初始化移至下一行。
  3. 您必须取消注释注释行(这就是您所需要的)。
  4. Debug.Log 总是寻找第一个坐标,我相信你想为每个坐标,将其更改为 i

试试这个。

i=0;
int[,] coordinates = new int[6853, 3];  

foreach (string line in dataLines) {

    lineValues = line.Split (' ');
    int coordinateX = int.Parse (lineValues [0]);
    int coordinateY = int.Parse (lineValues [1]);
    int coordinateZ = int.Parse (lineValues [2]);
    float intensity = float.Parse (lineValues [3]);

    coordinates [i, 0] = coordinateX;
    coordinates [i, 1] = coordinateY;
    coordinates [i, 2] = coordinateZ;

    Debug.Log(coordinates [i, 0]);
    i++;        
}