unity读取StreamingAssets中的txt内容,一行一行的打印
时间: 2024-09-28 11:05:35 浏览: 55
在Unity中,如果你想要从`StreamingAssets`目录读取文本文件(`.txt`),你可以使用C#的`TextAsset`类配合`StreamReader`。以下是简单的步骤:
1. 首先,在需要读取文件的地方创建一个`TextAsset`实例,通常在脚本中初始化:
```csharp
using UnityEngine;
using System.IO;
public class ReadTextFile : MonoBehaviour
{
public TextAsset textAsset; // 在Inspector中拖放你的.txt文件
void Start()
{
string filePath = Application.streamingAssetsPath + "/" + textAsset.name;
ReadFile(filePath);
}
private void ReadFile(string filePath)
{
try
{
using (StreamReader reader = new StreamReader(filePath))
{
string line;
while ((line = reader.ReadLine()) != null)
{
Debug.Log(line); // 打印每一行的内容
}
}
}
catch (FileNotFoundException e)
{
Debug.LogError("Failed to read file: " + e.Message);
}
}
}
```
在这个例子中,`textAsset.name`就是你在`StreamingAssets`里的txt文件名。
阅读全文
相关推荐












