-1

I have written two classes, one that writes to a txt file and one that reads from a text file. It works great on the editor but when I build the game for android and run it on android it does not work. The file cant be found. I am wondering how can I read and write to this file after the build. Here is the class I use to load the txt.

public class PlayerPositioner : MonoBehaviour
{

public GameObject player;
private float posx, posy;

void Start()
{
    string path = "Assets/Resources/Player.txt";

    //Read the text from directly from the test.txt file
    StreamReader reader = new StreamReader(path);
    string[] lines = System.IO.File.ReadAllLines(path);

    player.transform.position = new Vector2(float.Parse(lines[0]), float.Parse(lines[1]));

    reader.Close();
}
}
jack
  • 11
  • 1
  • 4

2 Answers2

0

you cant access resources folder with FileStream after build
you must use Resources.Load for access resources folder and load your assets and files, also you can use ScriptableObject if you want set some float or any var in your project and save in some file without need to use text editor for edit asset

0

Iis correct, once the software is compiled in your case the APK, you cannot use the System.IO library, since those files are not there, for that use the tools provided by Resource.Load Documentation

Now if you still want to read files stored in the device's memory, you must take into account that, depending on the platform, the storage location varies.

For that I use a very simple code:

public const string BaseFolder = "BaseFolder";
public static string getBasePath(){
    #if UNITY_EDITOR
        string path = Application.dataPath + $"/{BaseFolder}/" ;
        string path1 = Application.dataPath + $"/{BaseFolder}";
        if (!Directory.Exists(path1)) Directory.CreateDirectory(path1);
        if (!Directory.Exists(path)) Directory.CreateDirectory(path);
        return path;
    #elif UNITY_ANDROID
        string path = Application.persistentDataPath + $"/{BaseFolder}/";
        string path1 = Application.persistentDataPath + $"/{BaseFolder}";
        if (!Directory.Exists(path1)) Directory.CreateDirectory(path1);
        if (!Directory.Exists(path)) Directory.CreateDirectory(path);
        return path;
    #elif UNITY_IPHONE
        string path = Application.persistentDataPath + $"/{BaseFolder}/";
        string path1 = Application.persistentDataPath + $"/{BaseFolder}";
        if (!Directory.Exists(path1)) Directory.CreateDirectory(path1);
        if (!Directory.Exists(path)) Directory.CreateDirectory(path);
        return path;
    #else
        string path = Application.dataPath + $"/{BaseFolder}/";
        string path1 = Application.dataPath + $"/{BaseFolder}";
        if (!Directory.Exists(path1)) Directory.CreateDirectory(path1);
        if (!Directory.Exists(path)) Directory.CreateDirectory(path);
        return path;
    #endif
}
Elikill58
  • 4,050
  • 24
  • 23
  • 45
Jose Jaspe
  • 21
  • 1