我正在开发一个需要引用 .txt 文件的 HoloLens 项目。我将文件存储在 Unity 的“Resources”文件夹中,并让它们正常工作(通过 Unity 运行时):
string basePath = Application.dataPath;
string metadataPath = String.Format(@"\Resources\...\metadata.txt", list);
// If metadata exists, set title and introduction strings.
if (File.Exists(basePath + metadataPath))
{
using (StreamReader sr = new StreamReader(new FileStream(basePath + metadataPath, FileMode.Open)))
{
...
}
}
但是,在为 HoloLens 部署构建程序时,我能够运行代码,但它不起作用。没有显示任何资源,并且在检查 HoloLens Visual Studio 解决方案(通过在 Unity 中选择构建创建)时,我什至没有看到资源或 Assets 文件夹。我想知道我是否做错了什么,或者是否有一种特殊的方式来处理此类资源。
还有图像和声音文件...
foreach (string str in im)
{
spriteList.Add(Resources.Load<Sprite>(str));
}
字符串 'str' 有效;它与 Unity 一起工作得很好。但是,同样,它在通过 HoloLens 运行时不会加载任何内容。
最佳答案
您无法使用 StreamReader
读取资源目录或 File
类(class)。您必须使用 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;
Sprite - 单个:
Texture Type 设置为 Sprite(2D 和 UI)的图像 和
Sprite Mode 设置为 Single 的图像。
Sprite sprite = Resources.Load("spriteFile", typeof(Sprite)) as Sprite;
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 预制件:
GameObject prefab = Resources.Load("shipPrefab", typeof(GameObject)) as GameObject;
3D 网格(例如 FBX 文件)
Mesh model = Resources.Load("yourModelFileName", typeof(Mesh)) as Mesh;
3D 网格(来自 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”的子文件夹中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());
关于c# - 在 Unity 中使用资源文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48171273/