簡體   English   中英

Unity 3D 安卓和文件

[英]Unity 3D Android and File

我在使用 Android 和 Unity 3D 時遇到問題。 我有一個文件讀取代碼。 當我將代碼放在計算機上時,它可以工作。 但是,我的代碼不適用於 Android(移動)。 我該如何解決這個問題? 謝謝。

FileInfo theSourceFile = new FileInfo(filename);
    if (System.IO.File.Exists(fname))
    {
        StreamReader reader = theSourceFile.OpenText();
        string text = reader.ReadLine();
        print(string);
    }

編輯更新的代碼

string filename = "file.txt";
FileInfo theSourceFile = new FileInfo(filename);
filename = Application.persistentDataPath + "/"+filename;
System.IO.File.WriteAllText(filename,"Test");
    if (System.IO.File.Exists(filename))
    {
        StreamReader reader = theSourceFile.OpenText();
        string text = reader.ReadLine();
        print(string);
    }

您需要更改 android 設備的構建設置。 更改配置 >> 對外部(SD 卡)的寫訪問權限。

如果沒有,您的應用程序指向內部路徑,您需要在您的 android 設備中獲得 root 權限。

您必須在 Android 上使用Application.persistentDataPath才能讀取任何內容。

將其更改為string filename = Application.persistentDataPath + "/file.txt"; 並且您的代碼應該可以正常工作。

請記住,在讀取功能可以工作之前,您必須先寫入目錄。 所以file.txt必須首先存在於Application.persistentDataPath

例如

string filename = Application.persistentDataPath + "/file.txt";
System.IO.File.WriteAllText(filename,"Test");

編輯:

你的新代碼仍然無法工作,因為你有FileInfo theSourceFile = new FileInfo(filename); filename = Application.persistentDataPath + "/"+filename; . 這意味着該文件的名稱仍然無效 注意腳本執行順序 切換后,它在我的Android上工作。 下面是整個代碼。

string filename = "file.txt";
filename = Application.persistentDataPath + "/" + filename;
System.IO.FileInfo theSourceFile = new System.IO.FileInfo(filename);
System.IO.File.WriteAllText(filename, "Test");
if (System.IO.File.Exists(filename))
{
    System.IO.StreamReader reader = theSourceFile.OpenText();
    string text = reader.ReadLine();
    print(text);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM