您无法使用StreamReader
或File
类读取资源目录。您必须使用Resources.Load
.
1 .该路径是相对于您项目的 Assets 文件夹中的任何 Resources 文件夹的。
2、路径参数中不要包含.txt 、 .png 、.mp3等文件扩展名。
3 .当资源文件夹中有另一个文件夹时,使用正斜杠而不是反斜杠。反斜杠不起作用。
文本文件:
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;
精灵 - 单人:
纹理类型设置为Sprite(2D 和 UI)的图像和
Sprite Mode设置为Single的图像。
Sprite sprite = Resources.Load("spriteFile", typeof(Sprite)) as Sprite;
精灵 - 多个:
纹理类型设置为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文件,该文件位于Resources文件夹中名为“ Sound ”的子文件夹中,则使用正斜杠:
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());