您无法使用StreamReader 或File 类读取资源目录。您必须使用Resources.Load。
1。路径相对于您项目的 Assets 文件夹中的任何 Resources 文件夹。
2.不包括.txt、.png、等文件扩展名>.mp3 在路径参数中。
3。如果 Resources 文件夹中有另一个文件夹,请使用正斜杠而不是反斜杠。反斜杠不起作用。
文本文件:
TextAsset txtAsset = (TextAsset)Resources.Load("textfile", typeof(TextAsset));
string tileFile = txtAsset.text;
支持的TextAsset 格式:
txt .html .htm .xml .bytes .json .csv .yaml .fnt
声音文件:
AudioClip audio = Resources.Load("soundFile", typeof(AudioClip)) as AudioClip;
图像文件:
Texture2D texture = Resources.Load("textureFile", typeof(Texture2D)) as Texture2D;
精灵 - 单人:
Texture Type 设置为 Sprite(2D 和 UI)的图像 和
Sprite Mode 设置为 Single 的图像。
Sprite sprite = Resources.Load("spriteFile", typeof(Sprite)) as Sprite;
精灵 - 多个:
Texture Type 设置为 Sprite(2D 和 UI)的图像 和
Sprite Mode 设置为 Multiple 的图像。
Sprite[] sprite = Resources.LoadAll<Sprite>("spriteFile") as Sprite[];
视频文件(Unity >= 5.6):
VideoClip video = Resources.Load("videoFile", typeof(VideoClip)) as VideoClip;
游戏对象预制件:
GameObject prefab = Resources.Load("shipPrefab", typeof(GameObject)) as GameObject;
3D Mesh(如 FBX 文件)
Mesh model = Resources.Load("yourModelFileName", typeof(Mesh)) as Mesh;
3D Mesh(来自 GameObject Prefab)
MeshFilter modelFromGameObject = Resources.Load("yourGameObject", typeof(MeshFilter)) as MeshFilter;
Mesh loadedMesh = modelFromGameObject.sharedMesh; //Or design.mesh
3D 模型(作为游戏对象)
GameObject loadedObj = Resources.Load("yourGameObject") as GameObject;
//MeshFilter meshFilter = loadedObj.GetComponent<MeshFilter>();
//Mesh loadedMesh = meshFilter.sharedMesh;
GameObject object1 = Instantiate(loadedObj) as GameObject;
访问子文件夹中的文件:
例如,如果您有一个 shoot.mp3 文件,该文件位于名为“Sound”的子文件夹中,该子文件夹位于 Resources em> 文件夹,您使用正斜杠:
AudioClip audio = Resources.Load("Sound/shoot", typeof(AudioClip)) as AudioClip;
异步加载:
IEnumerator loadFromResourcesFolder()
{
//Request data to be loaded
ResourceRequest loadAsync = Resources.LoadAsync("shipPrefab", typeof(GameObject));
//Wait till we are done loading
while (!loadAsync.isDone)
{
Debug.Log("Load Progress: " + loadAsync.progress);
yield return null;
}
//Get the loaded data
GameObject prefab = loadAsync.asset as GameObject;
}
使用:StartCoroutine(loadFromResourcesFolder());