How to get Resources filepath on Android device?

Hello guys,

I went through some questions in the forum and none of the answers was relative to my question or it did not work.

In my project I have a Resources folder. I am not loading files from this folder, I only need to get the path of the file in this folder. In the Editor I have this and it is working perfectly:

filePath = “Assets/Resources/” + value.Enemy + “.dat”;
Output is: filePath = “Assets/Resources/“CliffSide”.dat”;

But now I need to release this game on Android device and it is not working. How should I get the path of the asset from the android build?

Please help.

The Resoures folder simply doens’t exist any more afer your build. The assets in the Resources folder get packed into the game’s archive for assets.

To solve this problem I created pre-compilation script which will run before the compilation; this script will list the names of the files you want to access later in text file

 #if UNITY_EDITOR
 using UnityEditor.Build;
 using UnityEditor;
 using System.IO;
 
 public class BM_AndroidBuildPrepartion : IPreprocessBuild
 {
     public int callbackOrder { get { return 0; } }
     public void OnPreprocessBuild(BuildTarget target, string path)
     {
         // Do the preprocessing here
         string[] fileEntries = Directory.GetFiles("Assets/Resources/Prefabs/alphabet", "*.prefab");
         System.IO.Directory.CreateDirectory("Assets/StreamingAssets/");
         using (StreamWriter sw = new StreamWriter("Assets/StreamingAssets/alphabet.txt", false))
         {
           
         foreach (string filename in fileEntries) {
                 sw.WriteLine(Path.GetFileNameWithoutExtension(filename));
         }
           
         }
     }
 }
 #endif

then I read the text file and you can access the files in same way but you have to put them inside your project in Assets/StreamingAssets/

   #if UNITY_ANDROID
        string  path = "jar:file://" + Application.dataPath + "!/assets/alphabet.txt";
          WWW wwwfile = new WWW(path);
          while (!wwwfile.isDone) { }
          var filepath = string.Format("{0}/{1}", Application.persistentDataPath, "alphabet.t");
          File.WriteAllBytes(filepath, wwwfile.bytes);
  
          StreamReader wr = new StreamReader(filepath);
              string line;
              while ((line = wr.ReadLine()) != null)
              {
              //your code
              }
   #endif
1 Like