docs.unity3d.com
Search Results for

    Show / Hide Table of Contents

    Use case: Manage an asset's files

    You can use the Unity Cloud Assets package to edit file metadata and download file content.

    The SDK supports different workflows for users with different roles.

    Organization or Asset Manager Project role Download files Edit files
    Asset Management Viewer no no
    Asset Management Consumer yes no
    Asset Management Contributor yes yes
    Organization Owner yes yes

    Before you start

    Before you start, you must:

    1. Set up a Unity scene in the Unity Editor with an Organization and Project browser. See Get started with Assets for more information.

    2. Have some assets in the cloud. There are several ways to do so:

      • You can create assets through the Get started with Assets.
      • You can upload assets from existing Unity assets; see the Asset Database Uploader sample.
      • You can create assets through the dashboard; see the Managing assets on the dashboard documentation.

    You should also have uploaded files to an asset; see the Create files use case.

    How do I...?

    List the files of an asset

    By default, when you get an asset, the files associated with are not included in the response. To get files associated to an asset:

    1. Open the AssetManagementBehaviour script you created.
    2. Add the following code to the end of the class:
    
    public List<IFile> Files { get; set; }
    
    public async Task GetAssetFiles()
    {
        Files = new List<IFile>();
    
        try
        {
            var fileList = CurrentAsset.ListFilesAsync(Range.All, CancellationToken.None);
            await foreach (var file in fileList)
            {
                Files.Add(file);
            }
        }
        catch (Exception e)
        {
            Debug.LogError(e);
            throw;
        }
    }
    
    

    The code snippet populates the Files property of the selected asset.

    Download a file

    To download the file of an asset, follow these steps:

    1. Open the AssetManagementBehaviour script you created.
    2. Add the following code to the end of the class:
    
    class LogProgress : IProgress<HttpProgress>
    {
        public void Report(HttpProgress value)
        {
            if (!value.DownloadProgress.HasValue) return;
    
            Debug.Log($"Download progress: {value.DownloadProgress * 100} %");
        }
    }
    
    public async Task DownloadAssetFile(IFile assetFile)
    {
        var path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
    
        var cancellationTokenSrc = new CancellationTokenSource();
        try
        {
            await using var destination = File.OpenWrite(Path.Combine(path, assetFile.Descriptor.Path));
    
            var progress = new LogProgress();
            await assetFile.DownloadAsync(destination, progress, cancellationTokenSrc.Token);
    
            Debug.Log($"Asset file downloaded: {assetFile.Descriptor.Path}.");
        }
        catch (Exception e)
        {
            Debug.LogError($"Failed to download asset file: {assetFile.Descriptor.Path}. {e}");
        }
    }
    
    

    The code snippet does the following:

    • Gets the files of an asset.
    • Downloads the selected file to the desktop.
    • Prints a message to the console when the download is complete OR prints an error message if the download fails.

    Update a file

    To update a file, follow these steps:

    1. Open the AssetManagementBehaviour script you created.
    2. Add the following code to the end of the class:
    
    public async Task UpdateAssetFile(IFile assetFile)
    {
        var fileUpdate = new FileUpdate(assetFile)
        {
            Description = Guid.NewGuid().ToString()[..3]
        };
    
        var cancellationTokenSrc = new CancellationTokenSource();
        await assetFile.UpdateAsync(fileUpdate, cancellationTokenSrc.Token);
        Debug.Log("File updated.");
    }
    
    

    The code snippet does the following:

    • Increments the index in the name of the file.
    • Prints a message to the console on success.

    Delete a file

    Deleting a file involves removing all references to the file from the asset. For more information see the use case for Removing a file reference from a dataset.

    Add the UI for interacting with files

    To create UI for interacting with files, follow these steps:

    1. In your Unity Project window, go to Assets > Scripts.
    2. Select and hold the Assets/Scripts folder.
    3. Go to Create > C# Script. Name your script UseCaseFileManagementExampleUI.
    4. Open the UseCaseFileManagementExampleUI script you created and replace the contents of the file with the following code sample:
    
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Threading;
    using System.Threading.Tasks;
    using Unity.Cloud.Assets;
    using Unity.Cloud.Common;
    using UnityEngine;
    
    public class UseCaseFileManagementExampleUI : IAssetManagementUI
    {
        readonly AssetManagementBehaviour m_Behaviour;
    
        public UseCaseFileManagementExampleUI(AssetManagementBehaviour behaviour)
        {
            m_Behaviour = behaviour;
        }
    
        public void OnGUI() { }
    }
    
    
    1. In the same script, replace the OnGUI function with the following code:
    
    IAsset m_CurrentAsset;
    Vector2 m_FilesScrollPosition;
    
    public void OnGUI()
    {
        if (!m_Behaviour.IsProjectSelected) return;
    
        if (m_Behaviour.CurrentAsset == null)
        {
            GUILayout.Label(" ! No asset selected !");
            return;
        }
    
        if (m_CurrentAsset != m_Behaviour.CurrentAsset)
        {
            m_CurrentAsset = m_Behaviour.CurrentAsset;
            m_Behaviour.Files = null;
        }
    
        GUILayout.BeginVertical();
    
        if (GUILayout.Button("Refresh Files") || m_Behaviour.Files == null)
        {
            _ = m_Behaviour.GetAssetFiles();
        }
    
        GUILayout.Space(5f);
    
        m_FilesScrollPosition = GUILayout.BeginScrollView(m_FilesScrollPosition, GUILayout.MaxHeight(Screen.height * 0.8f), GUILayout.Width(Screen.width * 0.3f));
    
        // Get a local copy of the list of asset files to avoid concurrent modification exceptions.
        var assetFiles = m_Behaviour.Files?.ToArray() ?? Array.Empty<IFile>();
        foreach (var assetFile in assetFiles)
        {
            DisplayAssetFile(assetFile);
        }
    
        GUILayout.EndScrollView();
    
        GUILayout.EndVertical();
    }
    
    void DisplayAssetFile(IFile assetFile)
    {
        GUILayout.BeginVertical(GUI.skin.box);
    
        GUILayout.Label($"{assetFile.Descriptor.Path}");
        if (!string.IsNullOrEmpty(assetFile.Description))
        {
            GUILayout.Label($"{assetFile.Description}");
        }
    
        GUILayout.Label($"Status: {assetFile.Status}");
    
        var createdDate = assetFile.AuthoringInfo?.Created.ToString("d") ?? "unknown";
        GUILayout.Label($"Created on: {createdDate}");
    
        GUILayout.Label($"Size: {assetFile.SizeBytes} bytes");
        GUILayout.Space(5f);
    
        GUILayout.BeginHorizontal();
    
        if (GUILayout.Button("Update"))
        {
            _ = m_Behaviour.UpdateAssetFile(assetFile);
        }
    
        if (GUILayout.Button("Download"))
        {
            _ = m_Behaviour.DownloadAssetFile(assetFile);
        }
    
        GUILayout.EndHorizontal();
    
        GUILayout.EndVertical();
    }
    
    
    1. Open the AssetManagementUI script you created and replace the contents of the Awake function with the following code:
       m_UI.Add(new OrganizationSelectionExampleUI(m_Behaviour));
       m_UI.Add(new ProjectSelectionExampleUI(m_Behaviour));
       m_UI.Add(new AssetSelectionExampleUI(m_Behaviour));
       m_UI.Add(new UseCaseFileManagementExampleUI(m_Behaviour));
    

    The code snippet does the following:

    • Displays a button to force refresh the list of files of the selected asset.
    • Displays each file of the selected asset with a UI buttons to update and download.

    Going further

    For more a more in-depth look at file management, see the Asset Database Uploader sample.

    In This Article
    Back to top
    Copyright © 2024 Unity Technologies — Trademarks and terms of use
    • Legal
    • Privacy Policy
    • Cookie Policy
    • Do Not Sell or Share My Personal Information
    • Your Privacy Choices (Cookie Settings)