使用 Cloud Storage for Unity 下載文件

Cloud Storage for Firebase 讓您可以快速輕鬆地從 Firebase 提供和管理的Cloud Storage 儲存桶下載檔案。

建立參考

若要下載文件,請先建立要下載的文件的 Cloud Storage 引用

您可以透過將子路徑附加到 Cloud Storage 儲存桶的根來建立引用,也可以從引用 Cloud Storage 中物件的現有gs://https:// URL 建立參考。

// Create a reference with an initial file path and name
StorageReference pathReference =
    storage.GetReference("images/stars.jpg");

// Create a reference from a Google Cloud Storage URI
StorageReference gsReference =
    storage.GetReferenceFromUrl("gs://bucket/images/stars.jpg");

// Create a reference from an HTTPS URL
// Note that in the URL, characters are URL escaped!
StorageReference httpsReference =
    storage.GetReferenceFromUrl("https://firebasestorage.googleapis.com/b/bucket/o/images%20stars.jpg");

下載文件

獲得參考後,您可以透過四種方式從 Cloud Storage 下載檔案:

  1. 從 URL 下載
  2. 下載到位元組數組
  3. 透過串流下載
  4. 下載到本地文件

您用於檢索文件的方法取決於您希望如何使用遊戲中的資料。

從 URL 下載

如果您想使用 Unity 的WWWUnityWebRequest的 URL,您可以透過呼叫GetDownloadUrlAsync()來取得檔案的下載 URL。

// Fetch the download URL
reference.GetDownloadUrlAsync().ContinueWithOnMainThread(task => {
    if (!task.IsFaulted && !task.IsCanceled) {
        Debug.Log("Download URL: " + task.Result);
        // ... now download the file via WWW or UnityWebRequest.
    }
});

下載到位元組數組

您可以使用GetBytesAsync()方法將檔案下載到記憶體中的位元組緩衝區。此方法會將文件的全部內容載入到記憶體中。如果您要求的檔案大於應用程式的可用內存,您的應用程式將會崩潰。為了防止記憶體問題,請確保將最大大小設為您知道應用程式可以處理的大小,或使用其他下載方法。

// Download in memory with a maximum allowed size of 1MB (1 * 1024 * 1024 bytes)
const long maxAllowedSize = 1 * 1024 * 1024;
reference.GetBytesAsync(maxAllowedSize).ContinueWithOnMainThread(task => {
    if (task.IsFaulted || task.IsCanceled) {
        Debug.LogException(task.Exception);
        // Uh-oh, an error occurred!
    }
    else {
        byte[] fileContents = task.Result;
        Debug.Log("Finished downloading!");
    }
});

透過串流下載

使用流下載檔案可讓您在載入資料時進行處理。這為您在處理下載時提供了最大的靈活性。呼叫GetStreamAsync()並將您自己的流處理器作為第一個參數傳遞。該委託將在帶有 Stream 的後台線程上調用,它允許您執行延遲密集型操作或計算,例如將內容儲存到磁碟。

// Download via a Stream
reference.GetStreamAsync(stream => {
    // Do something with the stream here.
    //
    // This code runs on a background thread which reduces the impact
    // to your framerate.
    //
    // If you want to do something on the main thread, you can do that in the
    // progress eventhandler (second argument) or ContinueWith to execute it
    // at task completion.
}, null, CancellationToken.None);

GetStreamAsync()在串流處理器之後接受一個可選參數,允許您取消操作或取得進度通知。

下載到本地文件

GetFileAsync()方法將檔案直接下載到本機。如果您的使用者希望在離線狀態下存取該文件或在其他應用程式中共用該文件,請使用此選項。

// Create local filesystem URL
string localUrl = "file:///local/images/island.jpg";

// Download to the local filesystem
reference.GetFileAsync(localUrl).ContinueWithOnMainThread(task => {
    if (!task.IsFaulted && !task.IsCanceled) {
        Debug.Log("File downloaded.");
    }
});

您可以將偵聽器附加到下載以監視下載進度。偵聽器遵循標準System.IProgress<T>介面。您可以使用StorageProgress類別的實例來提供您自己的Action<T>作為進度刻度的回呼。

// Create local filesystem URL
string localUrl = "file:///local/images/island.jpg";

// Start downloading a file
Task task = reference.GetFileAsync(localFile,
    new StorageProgress<DownloadState>(state => {
        // called periodically during the download
        Debug.Log(String.Format(
            "Progress: {0} of {1} bytes transferred.",
            state.BytesTransferred,
            state.TotalByteCount
        ));
    }), CancellationToken.None);

task.ContinueWithOnMainThread(resultTask => {
    if (!resultTask.IsFaulted && !resultTask.IsCanceled) {
        Debug.Log("Download finished.");
    }
});

處理錯誤

下載時出現錯誤的原因有很多,包括文件不存在或使用者沒有存取所需文件的權限。有關錯誤的更多資訊可以在文件的處理錯誤部分找到。

下一步

您也可以取得和更新儲存在 Cloud Storage 中的檔案的元資料