需要帮助读取 CSV 文件并从 LineRenderer 预制件克隆

问题描述 投票:0回答:1

我对 C# 和 Unity 还很陌生,我正在尝试可视化 3D 网络。我有 2 个 CSV 文件:其中一个包含 3 列数字,每列代表 3D 散点图的 X、Y 和 Z 坐标,其中每一行都是 3D 空间中的一个点。另一个 CSV 文件包含 2 列,分别表示连接第一个文件中的点的线的起点和终点。它从第一个文件中获取点的索引并将它们匹配在一起,形成边缘。 (例如:点 1 可能是 [3.56, 2.98, 7.12],点 2 可能是 [4.79, 2.10, 4.68],第二个 CSV 文件中的一行可能看起来像 [1, 2],代表一条边)。

我已经成功创建了一个球体预制件,使用读取点的 CSV 数据的脚本来“绘制”每个数据点。我想对数据点之间的每条线做同样的事情。

数据可视化截图:

这是我读取边缘数据的脚本,但我不确定为什么会收到“无法加载 CSV 文件”错误,即使我的边缘 CSV 文件显然不为空。

using System.Collections.Generic;
using UnityEngine;
using System.Collections;
using System;
using System.Text.RegularExpressions;
 
public class EdgeReader
{
    static string SPLIT_RE = @",(?=(?:[^""]*""[^""]*"")*(?![^""]*""))";
    static string LINE_SPLIT_RE = @"\r\n|\n\r|\n|\r";
    static char[] TRIM_CHARS = { '\"' };
    public TextAsset _edgeFile;
 
    public static List<Dictionary<string, object>> Read(string file)
    {
        var list = new List<Dictionary<string, object>>();
        TextAsset data = Resources.Load(file) as TextAsset;
        // Debug.Log("EdgeReader_Null");
        if (data == null)
        {
            Debug.LogError("Failed to load CSV file: " + file);
            return list;
        }
 
        var lines = Regex.Split(data.text, LINE_SPLIT_RE);
 
        if (lines.Length <= 1) return list;
 
        var header = Regex.Split(lines[0], SPLIT_RE);
        for (int i = 1; i < lines.Length; i++)
        {
            var values = Regex.Split(lines[i], SPLIT_RE);
            if (values.Length == 0 || values[0] == "") continue;
 
            int source, target;
            if (!int.TryParse(values[0], out source) || !int.TryParse(values[1], out target))
            {
                Debug.LogWarning("Failed to parse edge at line " + i);
                continue;
            }
 
            var edge = new Dictionary<string, object>();
            edge["source"] = source;
            edge["target"] = target;
 
            list.Add(edge);
        }
        return list;
    }
}

有什么想法吗?

c# unity-game-engine
1个回答
0
投票

您的问题就在这里

TextAsset data = Resources.Load(file) as TextAsset;

发生了两件事之一,要么您的

file
变量中保存的文件路径未指向可以加载的有效文件,要么
Reasources.Load
返回的值不可转换为
TextAsset
,无论哪种方式,这一行正在回归
null
。检查您的文件是否正确且位置正确,并且您将正确的路径传递到函数中。

我自己并不经常使用这个函数,但是从阅读文档来看,它似乎需要一个类型参数,就像这样

Reasources.Load<TextAsset>()
,如果你的类型不兼容,这会给你一个更好的错误消息。

© www.soinside.com 2019 - 2024. All rights reserved.