docs.unity3d.com
Search Results for

    Show / Hide Table of Contents

    Use case: Update 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 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:
    
    CancellationTokenSource m_DatasetCancellationSource;
    CancellationTokenSource m_FileCancellationSource;
    
    public IEnumerable<IDataset> Datasets { get; private set; }
    
    public IEnumerable<IFile> Files { get; set; }
    
    public async Task GetDataSetsAsync()
    {
        CleanDatasetCancellation();
    
        Datasets = null;
    
        if (CurrentAsset == null) return;
    
        m_DatasetCancellationSource = new CancellationTokenSource();
        var token = m_DatasetCancellationSource.Token;
    
        var datasets = new List<IDataset>();
        var datasetList = CurrentAsset.ListDatasetsAsync(Range.All, token);
        await foreach (var dataset in datasetList)
        {
            if (token.IsCancellationRequested) break;
    
            datasets.Add(dataset);
        }
    
        if (token.IsCancellationRequested) return;
    
        Datasets = datasets;
        CleanDatasetCancellation();
    }
    
    public async Task GetFilesAsync(IDataset dataset)
    {
        CleanFileCancellation();
    
        Files = null;
    
        if (dataset == null) return;
    
        m_FileCancellationSource = new CancellationTokenSource();
        var token = m_FileCancellationSource.Token;
    
        var files = new List<IFile>();
        var fileList = dataset.ListFilesAsync(Range.All, token);
        await foreach (var file in fileList)
        {
            files.Add(file);
        }
    
        Files = files;
        CleanFileCancellation();
    }
    
    void CleanDatasetCancellation()
    {
        if (m_DatasetCancellationSource != null)
        {
            m_DatasetCancellationSource.Cancel();
            m_DatasetCancellationSource.Dispose();
        }
        m_DatasetCancellationSource = null;
    }
    
    void CleanFileCancellation()
    {
        if (m_FileCancellationSource != null)
        {
            m_FileCancellationSource.Cancel();
            m_FileCancellationSource.Dispose();
        }
        m_FileCancellationSource = null;
    }
    
    

    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 DownloadFileAsync(IFile assetFile)
    {
        const string dialogHeader = "Download file to location:";
    
        var defaultFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
        var folder = UnityEditor.EditorUtility.OpenFolderPanel(dialogHeader, defaultFolder, "");
    
        if (string.IsNullOrEmpty(folder)) return;
    
        try
        {
            var filePath = Path.Combine(folder, assetFile.Descriptor.Path);
    
            // Create the necessary directories
            var directory = Path.GetDirectoryName(filePath);
            if (!string.IsNullOrEmpty(directory))
            {
                Directory.CreateDirectory(directory);
            }
    
            await using var destination = File.OpenWrite(filePath);
    
            var progress = new LogProgress();
            await assetFile.DownloadAsync(destination, progress, default);
    
            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

    The properties of the file that can be updated are the following:

    • Description
    • Tags

    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 UpdateFileAsync(IFile assetFile, IFileUpdate fileUpdate)
    {
        await assetFile.UpdateAsync(fileUpdate, CancellationToken.None);
        Debug.Log("File updated.");
        await assetFile.RefreshAsync(CancellationToken.None);
    }
    
    

    The code snippet does the following:

    • Updates the file with new data.
    • 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.

    Generating tags for a file

    The service can generate a list of suggested tags for any image files in the following supported formats:

    • JPEG
    • PNG
    • GIF
    • TIFF
    • WebP

    The desired tags can then be added to the file through the update method.

    To generate tags for a file, follow these steps:

    1. Open the AssetManagementBehaviour script you created.
    2. Add the following code to the end of the class:
    
    CancellationTokenSource TagGenerationCancellationSource;
    
    public async Task<IEnumerable<GeneratedTag>> GenerateTagsAsync(IFile file)
    {
        CancelTagGeneration();
    
        TagGenerationCancellationSource = new CancellationTokenSource();
    
        try
        {
            return await file.GenerateSuggestedTagsAsync(TagGenerationCancellationSource.Token);
        }
        catch (OperationCanceledException)
        {
            Debug.Log($"Cancelled tag generation for {file.Descriptor.Path}.");
        }
        catch (Exception e)
        {
            Debug.LogError(e);
        }
    
        return null;
    }
    
    public void CancelTagGeneration()
    {
        if (TagGenerationCancellationSource != null)
        {
            TagGenerationCancellationSource.Cancel();
            TagGenerationCancellationSource.Dispose();
        }
    
        TagGenerationCancellationSource = null;
    }
    
    

    The code snippet does the following:

    • Returns a list of generated tags for the file.
    • Prints any errors to the console.

    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.Linq;
    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_DatasetsScrollPosition;
    Vector2 m_FilesScrollPosition;
    
    IDataset m_CurrentDataset;
    IFile m_CurrentFile;
    FileUpdate m_FileUpdate;
    IEnumerable<GeneratedTag> m_GeneratedTags;
    
    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_CurrentDataset = null;
            m_Behaviour.Files = null;
            m_CurrentFile = null;
            m_FileUpdate = null;
            m_Behaviour.CancelTagGeneration();
            m_GeneratedTags = null;
            _ = m_Behaviour.GetDataSetsAsync();
        }
    
        if (m_Behaviour.Datasets == null)
        {
            GUILayout.Label("Loading datasets...");
            return;
        }
    
        GUILayout.BeginVertical();
    
        DisplayDatasetSelection();
    
        GUILayout.EndVertical();
    
        GUILayout.BeginVertical();
    
        DisplayFileSelection();
    
        GUILayout.EndVertical();
    
        GUILayout.BeginVertical();
    
        DisplaySelectedFile();
    
        GUILayout.EndVertical();
    }
    
    void DisplayDatasetSelection()
    {
        if (GUILayout.Button("Refresh Datasets"))
        {
            _ = m_Behaviour.GetDataSetsAsync();
        }
    
        GUILayout.Space(5f);
    
        m_DatasetsScrollPosition = GUILayout.BeginScrollView(m_DatasetsScrollPosition, GUILayout.MaxHeight(Screen.height * 0.8f), GUILayout.Width(Screen.width * 0.15f));
    
        DisplayDatasets(m_Behaviour.Datasets.ToArray());
    
        GUILayout.EndScrollView();
    }
    
    void DisplayDatasets(IReadOnlyCollection<IDataset> datasets)
    {
        if (datasets.Count == 0)
        {
            GUILayout.Label("No datasets.");
            return;
        }
    
        // Get a local copy of the list of asset files to avoid concurrent modification exceptions.
        foreach (var dataset in datasets)
        {
            GUILayout.BeginHorizontal();
    
            GUILayout.Label($"{dataset.Name}");
    
            if (GUILayout.Button("Select", GUILayout.Width(80)))
            {
                m_CurrentFile = null;
                m_FileUpdate = null;
                m_Behaviour.CancelTagGeneration();
                m_GeneratedTags = null;
                m_CurrentDataset = dataset;
                _ = m_Behaviour.GetFilesAsync(dataset);
            }
    
            GUILayout.EndHorizontal();
        }
    }
    
    void DisplayFileSelection()
    {
        if (m_CurrentDataset == null)
        {
            GUILayout.Label("! No dataset selected !");
            return;
        }
    
        if (m_Behaviour.Files == null)
        {
            GUILayout.Label("Loading files...");
            return;
        }
    
        if (GUILayout.Button("Refresh Files"))
        {
            _ = m_Behaviour.GetFilesAsync(m_CurrentDataset);
        }
    
        GUILayout.Space(5f);
    
        m_FilesScrollPosition = GUILayout.BeginScrollView(m_FilesScrollPosition, GUILayout.MaxHeight(Screen.height * 0.8f), GUILayout.Width(Screen.width * 0.2f));
    
        DisplayFiles(m_Behaviour.Files.ToArray());
    
        GUILayout.EndScrollView();
    }
    
    void DisplayFiles(IReadOnlyCollection<IFile> files)
    {
        if (files.Count == 0)
        {
            GUILayout.Label("No files.");
            return;
        }
    
        // Get a local copy of the list of asset files to avoid concurrent modification exceptions.
        foreach (var assetFile in files)
        {
            GUILayout.BeginHorizontal();
    
            GUILayout.Label($"{assetFile.Descriptor.Path}");
    
            if (GUILayout.Button("Select", GUILayout.Width(80)))
            {
                m_CurrentFile = assetFile;
                m_FileUpdate = new FileUpdate(assetFile);
    
                m_Behaviour.CancelTagGeneration();
                m_GeneratedTags = null;
            }
    
            if (GUILayout.Button("Download", GUILayout.Width(80)))
            {
                _ = m_Behaviour.DownloadFileAsync(assetFile);
            }
    
            GUILayout.EndHorizontal();
        }
    }
    
    void DisplaySelectedFile()
    {
        if (m_Behaviour.Files == null || !m_Behaviour.Files.Any()) return;
    
        if (m_CurrentFile == null)
        {
            GUILayout.Label("! No file selected !");
            return;
        }
    
        GUILayout.BeginVertical(GUI.skin.box);
    
        GUILayout.Label($"{m_CurrentFile.Descriptor.Path}");
    
        GUILayout.Label($"Status: {m_CurrentFile.Status}");
    
        var createdDate = m_CurrentFile.AuthoringInfo?.Created.ToString("d") ?? "unknown";
        GUILayout.Label($"Created on: {createdDate}");
    
        var modifiedDate = m_CurrentFile.AuthoringInfo?.Updated.ToString("d") ?? "unknown";
        GUILayout.Label($"Last modified on: {modifiedDate}");
    
        GUILayout.Label($"Size: {m_CurrentFile.SizeBytes} bytes");
    
        GUILayout.EndVertical();
    
        GUILayout.Space(5f);
    
        GUILayout.Label("Description:");
        m_FileUpdate.Description = GUILayout.TextField(m_FileUpdate.Description);
    
        GUILayout.Label("Tags:");
        var tags = string.Join(", ", m_FileUpdate.Tags ?? Array.Empty<string>());
        m_FileUpdate.Tags = GUILayout.TextField(tags).Split(',')
            .Select(x => x.Trim())
            .Where(x => !string.IsNullOrWhiteSpace(x))
            .ToArray();
    
        if (GUILayout.Button("Generate Tags"))
        {
            _ = GenerateTagsAsync();
        }
    
        DisplayGeneratedTags();
    
        GUILayout.Space(5f);
    
        if (GUILayout.Button("Update"))
        {
            _ = m_Behaviour.UpdateFileAsync(m_CurrentFile, m_FileUpdate);
        }
    }
    
    async Task GenerateTagsAsync()
    {
        m_GeneratedTags = null;
        m_GeneratedTags = await m_Behaviour.GenerateTagsAsync(m_CurrentFile);
    }
    
    void DisplayGeneratedTags()
    {
        if (m_GeneratedTags != null)
        {
            foreach (var tag in m_GeneratedTags)
            {
                GUILayout.BeginHorizontal();
    
                GUI.enabled = !m_FileUpdate.Tags?.Contains(tag.Value) ?? true;
    
                if (GUILayout.Button("Add"))
                {
                    m_FileUpdate.Tags ??= Array.Empty<string>();
                    m_FileUpdate.Tags = m_FileUpdate.Tags.Append(tag.Value).ToArray();
                }
    
                GUILayout.Label($"{tag.Value}, Confidence: {tag.Confidence:F3}");
    
                GUI.enabled = true;
    
                GUILayout.EndHorizontal();
            }
        }
    }
    
    
    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 select and download.
    • When a file is selected, displays a UI to generate tags and update the file's description and tags.
    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)