在我的资源文件夹中,我有一个图像子文件夹,我想从该文件夹中获取这些图像的所有文件名。
尝试了几个Resources.loadAll
之后获取 .name 但没有成功的方法
这是实现我在这里想做的事情的正确做法吗?
没有内置 API 可以执行此操作,因为信息不是在构建之后提供的。你甚至不能用里面的东西来做这个接受的答案 https://stackoverflow.com/a/52890273/3785314。这仅适用于编辑器。当您构建项目时,您的代码将失败。
该怎么做:
1。检测何时单击构建按钮或何时将要在OnPreprocessBuild https://docs.unity3d.com/ScriptReference/Build.IPreprocessBuildWithReport.OnPreprocessBuild.html功能。
2。获取所有文件名Directory.GetFiles
,将其序列化为json并保存到资源文件夹。我们使用 json 来更容易地读取单个文件名。您不必使用 json。您必须排除".meta"扩大。
步骤 1 和 2 在编辑器中完成。
3。构建后或运行时期间,您可以访问包含文件名的已保存文件TextAsset
with Resources.Load<TextAsset>("FileNames")
然后反序列化jsonTextAsset.text
.
下面是非常简化的示例。没有错误处理,这取决于您来实现。当您单击“构建”按钮时,下面的编辑器脚本会保存文件名:
[Serializable]
public class FileNameInfo
{
public string[] fileNames;
public FileNameInfo(string[] fileNames)
{
this.fileNames = fileNames;
}
}
class PreBuildFileNamesSaver : IPreprocessBuildWithReport
{
public int callbackOrder { get { return 0; } }
public void OnPreprocessBuild(UnityEditor.Build.Reporting.BuildReport report)
{
//The Resources folder path
string resourcsPath = Application.dataPath + "/Resources";
//Get file names except the ".meta" extension
string[] fileNames = Directory.GetFiles(resourcsPath)
.Where(x => Path.GetExtension(x) != ".meta").ToArray();
//Convert the Names to Json to make it easier to access when reading it
FileNameInfo fileInfo = new FileNameInfo(fileNames);
string fileInfoJson = JsonUtility.ToJson(fileInfo);
//Save the json to the Resources folder as "FileNames.txt"
File.WriteAllText(Application.dataPath + "/Resources/FileNames.txt", fileInfoJson);
AssetDatabase.Refresh();
}
}
在运行时,您可以使用以下示例检索保存的文件名:
//Load as TextAsset
TextAsset fileNamesAsset = Resources.Load<TextAsset>("FileNames");
//De-serialize it
FileNameInfo fileInfoLoaded = JsonUtility.FromJson<FileNameInfo>(fileNamesAsset.text);
//Use data?
foreach (string fName in fileInfoLoaded.fileNames)
{
Debug.Log(fName);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)