首先需要有一个excel表(可以自己手写),然后进行另存为选择CSV UTF-8(逗号分隔)(.csv)格式,然后拖入Unity对应的文件夹下即可使用
下面是操作流程
1.excel表
(小菜已经编辑好 可以直接拿来用)
ID | Name | love | dj |
1001 | 卷心菜1 | 打游戏 | 2 |
1002 | 卷心菜2 | Unity | 1 |
2.另存excel表
如上上图另存为CSV UTF-8(逗号分隔)(.csv)格式,这里注意有些用户可能没有此类型格式
点击文件->选项->高级->下滑找到Web选项->编码进行设置 如图所示
如果此方法仍然不行,可以将此excel表通过记事本进行编辑而打开 然后进行如图操作
保存替换即可 最后拖入Unity对应文件夹下即可
3.代码实现
创建一个空对象,绑定脚本,脚本内容如下
(这里运用了两种方式,使用其中一个即可)
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;
public class CSVReader : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
//读取方式1 TextAsset
CSVReadWithTextAsset();
//读取方式2 File
CSVReadWithFile();
}
private void CSVReadWithTextAsset()
{
// 资源加载方式 TextAsset读取
TextAsset ta = AssetDatabase.LoadAssetAtPath<TextAsset>("Assets/CSV/TestCSV.csv");
string info = ta.text;
string[] lines = info.Split("\r");
for (int i = 1; i < lines.Length - 1; i++)
{
SplitString(lines[i]);
}
}
private void CSVReadWithFile()
{
//File.IO读取方式
string path = Application.dataPath + "/CSV/TestCSV.csv";
if (File.Exists(path))
{
string info = File.ReadAllText(path);
string[] lines = info.Split("\r");
for (int i = 1; i < lines.Length - 1; i++)
{
SplitString(lines[i]);
}
}
}
/// <summary>
/// 将一行的数据切割
/// </summary>
/// <param name="line">第几行</param>
private void SplitString(string line)
{
string[] value = line.Split(",");
int id = int.Parse(value[0]);
string name = value[1];
string love = value[2];
int dj = int.Parse(value[3]);
Debug.Log($"ID为{id}的{name},爱好是{love},等级为{dj}");
}
}
4.效果展示
两种方式的效果
付出才有回报,祝愿大家都越来越优秀!
小菜不易,感谢观看,学到了就留下个支持的赞吧!
关注我,了解更多Unity相关知识哦!