Hi,
I need a way of counting the number of resources within the resource folder making it cross platform, specifically with android and ios.
All my levels are stored as json files within a sub directory of the resource folder. I have the following property to return a count of the levels.
public static int TotalMapCount
{
get
{
return Directory.GetFiles(Application.dataPath + "/resources/" + LevelDirectory, "*.json", SearchOption.AllDirectories).Length;
}
}
This works great when developing in Unity but as soon as I push it to android I get the following errors.
Directory ‘/data/app/mygame/base.apk/resources/data/levels’ not found.
Any ideas how I can solve this?
Thanks
There is no Resources directory in a built player, only resources.assets file. If you still need a resource count, you can create a custom build script, which will create a file with a list (or a count) of resources. And then at runtime, just read this resource:
public static class BuildUtils { //it mus be in Editor folder
[MenuItem("Build/With Resource Count")]
public static void CustomBuild() {
var count = Directory.GetFiles(
Application.dataPath + "/resources/" + LevelDirectory,
"*.json", SearchOption.AllDirectories);
File.WriteAllText(Application.dataPath + "/resources/count.txt", "count=" + count);
AssetDatabase.Refresh();
BuildPipeline.BuildPlayer(
new[] { "Assets/Scenes/MyScene.unity" },
"path/to/built/player",
BuildTarget.Android,
BuildOptions.None);
}
}
public class SomeBehavior : MonoBehaviour {
void Start() {
var textAsset = Resources.Load<TextAsset>("count.txt");
Debug.Log(textAsset.text);
}
}
You can use Resources.LoadAll(string path)
which returns an Object[]
and then use the array length as your count. Just be sure to unload those resources once your done, otherwise they will stay in memory. Something like this:
private static int totalMapCount = -1;
public static int TotalMapCount
{
get
{
if (totalMapCount == -1)
{
Object[] maps = Resources.LoadAll("LevelDirectory");
totalMapCount = maps.Length;
Resources.UnloadUnusedAssets();
}
return totalMapCount;
}
}
you can always add a textAssets with the data needed for the folder managing likes the number of files, list of files and etc…