Создайте ссылку на облачное хранилище с помощью Cloud Storage for Unity.

Your files are stored in a Cloud Storage bucket. The files in this bucket are presented in a hierarchical structure, just like the file system on your local hard disk, or the data in the Firebase Realtime Database . By creating a reference to a file, your app gains access to it. These references can then be used to upload or download data, get or update metadata or delete the file. A reference can either point to a specific file or to a higher level node in the hierarchy.

Если вы использовали Firebase Realtime Database , эти пути должны показаться вам очень знакомыми. Однако ваши файловые данные хранятся в Cloud Storage , а не в Realtime Database .

Создать ссылку

Создайте ссылку для загрузки, скачивания или удаления файла, а также для получения или обновления его метаданных. Ссылку можно рассматривать как указатель на файл в облаке. Ссылки являются легковесными, поэтому вы можете создать столько ссылок, сколько вам нужно. Они также могут быть использованы повторно для различных операций.

Ссылки создаются из сервиса Firebase.Storage.FirebaseStorage в вашем приложении Firebase путем вызова метода GetReferenceFromUrl() и передачи URL-адреса вида gs://<your-cloud-storage-bucket> . Этот URL-адрес можно найти в разделе «Хранилище» консоли Firebase .

// Get a reference to the storage service, using the default Firebase App
FirebaseStorage storage = FirebaseStorage.DefaultInstance;

// Create a storage reference from our storage service
StorageReference storageRef =
    storage.GetReferenceFromUrl("gs://<your-cloud-storage-bucket>");

Вы можете создать ссылку на местоположение, расположенное ниже в дереве, например, 'images/space.jpg' , используя метод child для уже существующей ссылки.

// Create a child reference
// imagesRef now points to "images"
StorageReference imagesRef = storageRef.Child("images");

// Child references can also take paths delimited by '/' such as:
// "images/space.jpg".
StorageReference spaceRef = imagesRef.Child("space.jpg");
// spaceRef now points to "images/space.jpg"
// imagesRef still points to "images"

// This is equivalent to creating the full referenced
StorageReference spaceRefFull = storage.GetReferenceFromUrl(
    "gs://<your-cloud-storage-bucket>/images/space.jpg");

Для навигации вверх по файловой иерархии можно также использовать методы Parent и Root . Parent перемещает на один уровень вверх, а Root — до самого верха.

// Parent allows us to move to the parent of a reference
// imagesRef now points to 'images'
StorageReference imagesRef = spaceRef.Parent;

// Root allows us to move all the way back to the top of our bucket
// rootRef now points to the root
StorageReference rootRef = spaceRef.Root;

Child , Parent и Root можно объединять в цепочку несколько раз, поскольку каждый из них возвращает ссылку. Исключением является объект Parent объекта Root , который является недопустимым StorageReference .

// References can be chained together multiple times
// earthRef points to "images/earth.jpg"
StorageReference earthRef =
    spaceRef.Parent.Child("earth.jpg");

// nullRef is null since the parent of root is an invalid StorageReference
StorageReference nullRef = spaceRef.Root.Parent;

Референтные методы

Для лучшего понимания файлов, на которые они указывают, можно просмотреть ссылки, используя свойства Path , Name и Bucket . Эти свойства позволяют получить полный путь к файлу, его имя и название корзины.

// Reference's path is: "images/space.jpg"
// This is analogous to a file path on disk
string path = spaceRef.Path;

// Reference's name is the last segment of the full path: "space.jpg"
// This is analogous to the file name
string name = spaceRef.Name;

// Reference's bucket is the name of the storage bucket where files are stored
string bucket = spaceRef.Bucket;

Ограничения на использование ссылок

Ссылочные пути и имена могут содержать любую последовательность допустимых символов Unicode, но на них накладываются определенные ограничения, в том числе:

  1. Общая длина reference.Path должен быть от 1 до 1024 байт при кодировке UTF-8.
  2. Символы возврата каретки и перевода строки запрещены.
  3. Избегайте использования # , [ , ] , * или ? , поскольку они плохо работают с другими инструментами, такими как Firebase Realtime Database или gsutil .

Полный пример

FirebaseStorage storage = FirebaseStorage.DefaultInstance;

// Points to the root reference
StorageReference storageRef =
    storage.GetReferenceFromUrl("gs://<your-bucket-name>");

// Points to "images"
StorageReference imagesRef = storageRef.Child("images");

// Points to "images/space.jpg"
// Note that you can use variables to create child values
string filename = "space.jpg";
StorageReference spaceRef = imagesRef.Child(filename);

// File path is "images/space.jpg"
string path = spaceRef.Path;

// File name is "space.jpg"
string name = spaceRef.Name;

// Points to "images"
StorageReference imagesRef = spaceRef.Parent;

Следующие шаги

Далее давайте узнаем, как загружать файлы в Cloud Storage .