Use case: Manage asset collections in a project
You can use the Unity Cloud Assets package to create, delete, and edit an asset collection in a project.
Organization or Asset Manager Project role | List collections | Create/delete/update collections | Add/remove assets in collections |
---|---|---|---|
Asset Management Viewer |
yes | no | no |
Asset Management Consumer |
yes | no | no |
Asset Management Contributor |
yes | no | no |
Organization Owner |
yes | yes | yes |
Before you start
Before you start, you must:
Set up a Unity scene in the Unity Editor with an Organization and Project browser. See Get started with Assets for more information.
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.
How do I...?
List the collections in a project
To list the existing collections in a Project, follow these steps:
- Open the
AssetManagementBehaviour
script you created. - Add the following code to the end of the class:
public IEnumerable<IAssetCollection> AssetCollections { get; private set; }
public IAssetCollection CurrentCollection { get; private set; }
public AssetCollectionUpdate CurrentCollectionUpdate { get; private set; }
public List<AssetId> CurrentCollectionAssetIds { get; } = new();
public async Task ListProjectAssetCollectionsAsync()
{
CurrentCollection = null;
var results = CurrentProject.ListCollectionsAsync(Range.All, CancellationToken.None);
var collections = new List<IAssetCollection>();
await foreach (var collection in results)
{
collections.Add(collection);
}
AssetCollections = collections;
}
public async Task SetCurrentCollection(IAssetCollection collection)
{
CurrentCollectionUpdate = null;
CurrentCollection = collection;
if (CurrentCollection != null)
{
var properties = await CurrentCollection.GetPropertiesAsync(CancellationToken.None);
CurrentCollectionUpdate = new AssetCollectionUpdate
{
Name = collection.Name,
Description = properties.Description
};
await RefreshCollectionAssets();
}
}
async Task RefreshCollectionAssets()
{
CurrentCollectionAssetIds.Clear();
var searchFilter = new AssetSearchFilter();
searchFilter.Collections.WhereContains(CurrentCollection.Descriptor.Path);
var assetList = CurrentProject.QueryAssets().SelectWhereMatchesFilter(searchFilter).ExecuteAsync(CancellationToken.None);
await foreach (var asset in assetList)
{
if (!m_Behaviour.TryGetAssetProperties(asset.Descriptor.AssetVersion, out var properties))
{
properties = await asset.GetPropertiesAsync(CancellationToken.None);
m_Behaviour.IncludeProperties(asset.Descriptor, properties);
}
CurrentCollectionAssetIds.Add(asset.Descriptor.AssetId);
}
}
The code snippet does the following:
- Populates a list of the collections in the selected Project.
- Holds a reference to the selected collection.
Create an asset collection
To create an asset collection, follow these steps:
- Open the
AssetManagementBehaviour
script you created. - Add the following code to the end of the class:
public async Task CreateAssetCollectionAsync(CollectionPath newPath)
{
var name = newPath.GetLastComponentOfPath();
var newCollection = new AssetCollectionCreation(name, "A collection generated by the use-case example.")
{
ParentPath = newPath.GetParentPath()
};
try
{
await CurrentProject.CreateCollectionLiteAsync(newCollection, CancellationToken.None);
Debug.Log("Collection created at path: " + newPath);
// Refresh the list of collections.
await ListProjectAssetCollectionsAsync();
}
catch (Exception e)
{
Debug.LogError(e.Message);
}
}
The code snippet does the following:
- Creates a new asset collection with the specified name and parent collection.
- Updates the list of collections in the selected Project.
- Prints a message to the console on success.
Update an asset collection
To update an asset collection, follow these steps:
- Open the
AssetManagementBehaviour
script you created. - Add the following code to the end of the class:
public async Task UpdateProjectAssetCollectionAsync(IAssetCollectionUpdate update)
{
await CurrentCollection.UpdateAsync(update, default);
Debug.Log("Collection updated.");
}
The code snippet does the following:
- Updates the selected collection's description by incrementing a counter within the text.
- Prints a message to the console on success.
Delete an asset collection
To delete an asset collection, follow these steps:
- Open the
AssetManagementBehaviour
script you created. - Add the following code to the end of the class:
public async Task DeleteAssetCollectionAsync(IAssetCollection collection)
{
await CurrentProject.DeleteCollectionAsync(collection.Descriptor.Path, CancellationToken.None);
// Refresh the list of collections.
await ListProjectAssetCollectionsAsync();
Debug.Log("Collection deleted.");
}
The code snippet does the following:
- Deletes the selected collection from the Project.
- Refreshes the list of collections in the Project.
- Prints a message to the console on success.
Move an asset collection
To move an asset collection either to nest it under another collection or re-parent at the root of the project, follow these steps:
- Open the
AssetManagementBehaviour
script you created. - Add the following code to the end of the class:
public async Task MoveProjectAssetCollectionAsync(CollectionPath newPath)
{
await CurrentCollection.MoveToNewPathAsync(newPath, CancellationToken.None);
await ListProjectAssetCollectionsAsync();
Debug.Log("Collection successfully moved to new path: " + newPath);
}
The code snippet does the following:
- Moves the selected collection to the specified parent collection.
- Prints a message to the console on success.
Add an asset to a collection
To add an asset to a collection, follow these steps:
- Open the
AssetManagementBehaviour
script you created. - Add the following code to the end of the class:
public async Task LinkAssetToCollectionAsync(AssetId assetId)
{
await CurrentCollection.LinkAssetsAsync(new[] {assetId}, CancellationToken.None);
Debug.Log("Asset added to collection.");
await RefreshCollectionAssets();
}
The code snippet does the following:
- Adds the selected asset to the selected collection.
- Prints a message to the console on success.
Remove an asset from a collection
To remove an asset from a collection, follow these steps:
- Open the
AssetManagementBehaviour
script you created. - Add the following code to the end of the class:
public async Task UnlinkAssetFromCollectionAsync(AssetId assetId)
{
await CurrentCollection.UnlinkAssetsAsync(new[] {assetId}, CancellationToken.None);
Debug.Log("Asset added to collection.");
await RefreshCollectionAssets();
}
The code snippet does the following:
- Removes the target asset from the selected collection.
- Prints a message to the console on success.
Add the UI for listing and managing collections
To create UI for listing and managing collections, follow these steps:
- In your Unity Project window, go to Assets > Scripts.
- Select and hold the
Assets/Scripts
folder. - Go to Create > C# Script. Name your script
UseCaseManageCollectionsExampleUI
. - Open the
UseCaseManageCollectionsExampleUI
script you created and replace the contents of the file with the following code sample:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Unity.Cloud.Assets;
using Unity.Cloud.Common;
using UnityEngine;
public class UseCaseManageCollectionsExampleUI : IAssetManagementUI
{
readonly AssetManagementBehaviour m_Behaviour;
public UseCaseManageCollectionsExampleUI(AssetManagementBehaviour behaviour)
{
m_Behaviour = behaviour;
}
public void OnGUI() { }
}
- In the same script, replace the
OnGUI
function with the following code:
IAssetProject m_CurrentProject;
Vector2 m_CollectionListScrollPosition;
string m_NewCollectionName = "";
string m_NewParentPath = "";
public void OnGUI()
{
if (!m_Behaviour.IsProjectSelected) return;
if (m_Behaviour.CurrentProject != m_CurrentProject)
{
m_CurrentProject = m_Behaviour.CurrentProject;
_ = m_Behaviour.ListProjectAssetCollectionsAsync();
}
ListCollections();
DrawCurrentCollection();
DrawAssets();
GUILayout.FlexibleSpace();
}
void ListCollections()
{
GUILayout.BeginVertical();
CreateNewCollection();
GUILayout.Space(15f);
GUILayout.Label("Available Collections:");
if (GUILayout.Button("Refresh collection list"))
{
_ = m_Behaviour.ListProjectAssetCollectionsAsync();
}
if (m_Behaviour.AssetCollections != null)
{
m_CollectionListScrollPosition = GUILayout.BeginScrollView(m_CollectionListScrollPosition);
// Hold a local reference to the collections to avoid concurrent modification exceptions.
var collections = m_Behaviour.AssetCollections.ToArray();
foreach (var collection in collections)
{
GUILayout.BeginHorizontal();
DrawCollection(collection);
GUILayout.EndHorizontal();
}
GUILayout.EndScrollView();
}
GUILayout.FlexibleSpace();
GUILayout.EndVertical();
}
void CreateNewCollection()
{
GUILayout.Label("Create New Collection");
GUILayout.Label("Collection Path:");
m_NewCollectionName = GUILayout.TextField(m_NewCollectionName);
if (GUILayout.Button("Create"))
{
_ = m_Behaviour.CreateAssetCollectionAsync(m_NewCollectionName);
}
}
void DrawCollection(IAssetCollection collection)
{
GUILayout.Label($"{collection.Name}", GUILayout.MaxWidth(Screen.width * 0.2f));
GUI.enabled = collection != m_Behaviour.CurrentCollection;
if (GUILayout.Button("Select", GUILayout.Width(60)))
{
_ = m_Behaviour.SetCurrentCollection(collection);
}
GUI.enabled = true;
if (GUILayout.Button("Delete"))
{
_ = m_Behaviour.DeleteAssetCollectionAsync(collection);
}
}
void DrawCurrentCollection()
{
if (m_Behaviour.CurrentCollection == null)
{
GUILayout.Label("! No collection selected !");
return;
}
if (m_Behaviour.CurrentCollectionUpdate == null)
{
GUILayout.Label("Loading collection...");
return;
}
GUILayout.BeginVertical();
GUILayout.Label($"{m_Behaviour.CurrentCollection.ParentPath}::{m_Behaviour.CurrentCollection.Name}");
GUILayout.Label("Name: ");
m_Behaviour.CurrentCollectionUpdate.Name = GUILayout.TextField(m_Behaviour.CurrentCollectionUpdate.Name);
GUILayout.Label("Description: ");
m_Behaviour.CurrentCollectionUpdate.Description = GUILayout.TextArea(m_Behaviour.CurrentCollectionUpdate.Description, GUILayout.MinHeight(60));
if (GUILayout.Button("Update"))
{
_ = m_Behaviour.UpdateProjectAssetCollectionAsync(m_Behaviour.CurrentCollectionUpdate);
}
GUILayout.Space(10f);
GUILayout.Label("New parent path: ");
m_NewParentPath = GUILayout.TextField(m_NewParentPath);
if (GUILayout.Button("Reparent Collection"))
{
_ = m_Behaviour.MoveProjectAssetCollectionAsync(m_NewParentPath);
}
GUILayout.EndVertical();
}
void DrawAssets()
{
GUILayout.BeginVertical();
var currentAssetId = m_Behaviour.CurrentAsset?.Descriptor.AssetId ?? AssetId.None;
var currentAssetVersion = m_Behaviour.CurrentAsset?.Descriptor.AssetVersion ?? AssetVersion.None;
AssetProperties? currentAssetProperties = m_Behaviour.TryGetAssetProperties(currentAssetVersion, out var properties) ? properties : null;
GUILayout.Label($"Selected Asset: {currentAssetProperties?.Name ?? "! No asset selected !"}");
var assetIds = m_Behaviour.CurrentCollectionAssetIds;
if (currentAssetProperties.HasValue)
{
if (assetIds.Any(id => id == currentAssetId))
{
GUILayout.Label("Asset is in collection.");
}
else if (GUILayout.Button("Add asset to collection"))
{
_ = m_Behaviour.LinkAssetToCollectionAsync(currentAssetId);
}
}
GUILayout.Space(15f);
GUILayout.Label("Assets in collection:");
foreach (var assetId in assetIds)
{
DrawAsset(assetId);
}
GUILayout.EndVertical();
}
void DrawAsset(AssetId assetId)
{
AssetProperties? properties = m_Behaviour.TryGetAssetProperties(assetId, out var p) ? p : null;
GUILayout.BeginHorizontal();
GUILayout.Label($"{properties?.Name ?? assetId.ToString()}");
if (GUILayout.Button("Remove from collection"))
{
_ = m_Behaviour.UnlinkAssetFromCollectionAsync(assetId);
}
GUILayout.EndHorizontal();
}
- Open the
AssetManagementUI
script you created and replace the contents of theAwake
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 UseCaseManageCollectionsExampleUI(m_Behaviour));
The code snippet does the following:
- Displays a list of the selected Project's collections.
- Displays UI buttons and necessary text fields to create a new collection and to select a collection.
- Displays UI buttons to update and delete the selected collection.
- Displays a text field and UI button to re-parent the selected collection to another collection.
- Displays a UI button to add the selected asset to the selected collection.
- Displays the list of assets in the selected collection. Each asset has a UI button to remove it from the selected collection.