Use case: Manage an asset's metadata
You can use the Unity Cloud Assets package to:
- View the metadata of an asset.
- Add or remove a metadata entry from an asset.
- Update the value of the metadata entry of an asset.
The SDK supports different workflows for users with different roles.
Organization or Asset Manager Project role | View metadata | Update metadata |
---|---|---|
Asset Management Viewer |
yes | no |
Asset Management Consumer |
yes | no |
Asset Management Contributor |
yes | yes |
Organization Owner |
yes | yes |
Before you start
Before you start, you need 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...?
View the metadata of an asset
To fetch the metadata of an asset, follow these steps:
- Open the
AssetManagementBehaviour
script you created. - Add the following code to the end of the class:
IReadOnlyMetadataContainer MetadataContainer { get; set; }
public IReadOnlyDictionary<string, MetadataValue> Metadata { get; private set; }
public async Task GetMetadataAsync(IReadOnlyMetadataContainer metadataContainer)
{
MetadataContainer = metadataContainer;
Metadata = null;
if (metadataContainer == null) return;
var result = MetadataContainer.Query().ExecuteAsync(CancellationToken.None);
var metadata = new Dictionary<string, MetadataValue>();
await foreach (var item in result)
{
metadata[item.Key] = item.Value;
}
Metadata = metadata;
Debug.Log("Successfully fetched metadata.");
}
The code snippet populates a dictionary of metadata.
Add or update entries in an asset's metadata
[!NOTE] The keys for metadata must already exist in your organization's library. To add and remove metadata keys, see the Manage the field definitions in an organization.
To add or update an entry in the metadata of an asset, follow these steps:
- Open the
AssetManagementBehaviour
script you created. - Add the following code to the end of the class:
public async Task UpdateAsync(string key, MetadataValue value)
{
try
{
if (MetadataContainer is not IMetadataContainer metadataContainer)
{
throw new NotSupportedException();
}
await metadataContainer.AddOrUpdateAsync(key, value, CancellationToken.None);
Debug.Log("Successfully updated metadata.");
}
catch (Exception e)
{
Debug.LogError("Could not update metadata: " + e.Message);
}
}
The code snippet does the following:
- Adds or updates the specified metadata key with the provided value for the selected asset.
- Prints a message to the console on success.
Remove an entry from an asset's metadata
To remove an entry from the metadata:
- Open the
AssetManagementBehaviour
script you created. - Add the following code to the end of the class:
public async Task RemoveMetadata(string key)
{
try
{
if (MetadataContainer is not IMetadataContainer metadataContainer)
{
throw new NotSupportedException();
}
await metadataContainer.RemoveAsync(new[] {key}, CancellationToken.None);
Debug.Log("Successfully removed metadata.");
}
catch (Exception e)
{
Debug.LogError("Could not remove metadata: " + e.Message);
}
}
The code snippet does the following:
- Removes the specified metadata key from the selected asset.
- Prints a message to the console on success.
Add the UI for viewing and modifying the metadata of an asset
To create the UI, begin by creating helper classes:
- In your Unity Project window, go to Assets > Scripts.
- Select and hold the
Assets/Scripts
folder. - Go to Create > C# Script. Name your script
BooleanMetadataValueDisplayer
. - Open the
BooleanMetadataValueDisplayer
script you created and replace the content of the file with the following code sample:
public interface IMetadataValueDisplayer
{
MetadataValue Value { get; }
bool IsValid { get; }
void Display();
}
public class BooleanMetadataValueDisplayer : IMetadataValueDisplayer
{
readonly BooleanMetadata m_Boolean;
public MetadataValue Value => m_Boolean;
public bool IsValid => true;
public BooleanMetadataValueDisplayer(BooleanMetadata value)
{
m_Boolean = value;
}
public void Display()
{
m_Boolean.Value = GUILayout.Toggle(m_Boolean.Value, "Is enabled");
}
}
- Repeat steps 3 and 4 to create the subsequent helper classes with the following scripts and code samples:
- For the
NumberMetadataValueDisplayer
script, use the following code sample:
public class NumberMetadataValueDisplayer : IMetadataValueDisplayer
{
readonly NumberMetadata m_Number;
public MetadataValue Value => m_Number;
public bool IsValid { get; private set; }
public NumberMetadataValueDisplayer(NumberMetadata value)
{
m_Number = value;
}
public void Display()
{
var number = GUILayout.TextField(m_Number.Value.ToString());
if (string.IsNullOrWhiteSpace(number))
{
number = "0";
}
if (number.StartsWith('.'))
{
number = number.Insert(0, "0");
}
else if (number.EndsWith('.'))
{
number = number.Insert(number.Length, "0");
}
if (double.TryParse(number, out var parsedNumber))
{
m_Number.Value = parsedNumber;
IsValid = true;
}
else
{
IsValid = false;
GUILayout.Label("Invalid number");
}
}
}
- For the
UrlMetadataValueDisplayer
script, use the following code sample:
public class UrlMetadataValueDisplayer : IMetadataValueDisplayer
{
readonly UrlMetadata m_UrlMetadata;
string m_Url;
public MetadataValue Value => m_UrlMetadata;
public bool IsValid { get; private set; }
public UrlMetadataValueDisplayer(UrlMetadata value)
{
m_UrlMetadata = value;
m_Url = m_UrlMetadata.Uri.ToString();
}
public void Display()
{
m_UrlMetadata.Label = GUILayout.TextField(m_UrlMetadata.Label);
m_Url = GUILayout.TextField(m_Url);
if (Uri.TryCreate(m_Url, UriKind.Absolute, out var uri))
{
m_UrlMetadata.Uri = uri;
IsValid = true;
}
else
{
IsValid = false;
GUILayout.Label("Invalid URL");
}
}
}
- For the
SingleSelectionMetadataValueDisplayer
script, use the following code sample:
public class SingleSelectionMetadataValueDisplayer : IMetadataValueDisplayer
{
readonly SingleSelectionMetadata m_SelectionMetadata;
readonly HashSet<string> m_AcceptedValues = new();
public MetadataValue Value => m_SelectionMetadata;
public bool IsValid { get; private set; }
public SingleSelectionMetadataValueDisplayer(SingleSelectionMetadata value, FieldDefinitionDescriptor definitionDescriptor)
{
m_SelectionMetadata = value;
_ = PopulateAcceptedValues(definitionDescriptor);
}
async Task PopulateAcceptedValues(FieldDefinitionDescriptor descriptor)
{
var fieldDefinition = await PlatformServices.AssetRepository.GetFieldDefinitionAsync(descriptor, default);
if (fieldDefinition.Type == FieldDefinitionType.Selection)
m_AcceptedValues.UnionWith(fieldDefinition.AsSelectionFieldDefinition().AcceptedValues);
}
public void Display()
{
GUILayout.Label("Accepted values: " + string.Join(", ", m_AcceptedValues));
m_SelectionMetadata.SelectedValue = GUILayout.TextField(m_SelectionMetadata.SelectedValue);
IsValid = m_AcceptedValues.Contains(m_SelectionMetadata.SelectedValue);
if (!IsValid)
{
GUILayout.Label("Invalid value");
}
}
}
- For the
MultiSelectionMetadataValueDisplayer
script, use the following code sample:
public class MultiSelectionMetadataValueDisplayer : IMetadataValueDisplayer
{
readonly MultiSelectionMetadata m_SelectionMetadata;
readonly HashSet<string> m_AcceptedValues = new();
string m_SelectedValues;
public MetadataValue Value => m_SelectionMetadata;
public bool IsValid { get; private set; }
public MultiSelectionMetadataValueDisplayer(MultiSelectionMetadata value, FieldDefinitionDescriptor descriptor)
{
m_SelectionMetadata = value;
m_SelectedValues = string.Join(", ", m_SelectionMetadata.SelectedValues);
_ = PopulateAcceptedValues(descriptor);
}
async Task PopulateAcceptedValues(FieldDefinitionDescriptor descriptor)
{
var fieldDefinition = await PlatformServices.AssetRepository.GetFieldDefinitionAsync(descriptor, default);
if (fieldDefinition.Type == FieldDefinitionType.Selection)
m_AcceptedValues.UnionWith(fieldDefinition.AsSelectionFieldDefinition().AcceptedValues);
}
public void Display()
{
GUILayout.Label("Accepted values: " + string.Join(", ", m_AcceptedValues));
m_SelectedValues = GUILayout.TextField(m_SelectedValues);
IsValid = true;
var selectedValues = new List<string>();
var selectedValuesString = m_SelectedValues.Split(',');
foreach (var selectedValue in selectedValuesString)
{
var value = selectedValue.Trim();
if (string.IsNullOrWhiteSpace(value)) continue;
if (!m_AcceptedValues.Contains(value))
{
IsValid = false;
break;
}
selectedValues.Add(value);
}
if (!IsValid)
{
GUILayout.Label("Invalid value");
}
else
{
m_SelectionMetadata.SelectedValues = selectedValues;
}
}
}
- For the
TextMetadataValueDisplayer
script, use the following code sample:
public class TextMetadataValueDisplayer : IMetadataValueDisplayer
{
readonly StringMetadata m_Text;
public MetadataValue Value => m_Text;
public bool IsValid => true;
public TextMetadataValueDisplayer(StringMetadata value)
{
m_Text = value;
}
public void Display()
{
m_Text.Value = GUILayout.TextField(m_Text.Value);
}
}
To complete the UI, 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
UseCaseAssetMetadataExampleUI
. - Open the
UseCaseAssetMetadataExampleUI
script you created and replace the content of the file with the following code sample:
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Unity.Cloud.Assets;
using UnityEngine;
public class UseCaseAssetCollectionExampleUI : IAssetManagementUI
{
readonly AssetManagementBehaviour m_Behaviour;
public UseCaseAssetCollectionExampleUI(AssetManagementBehaviour behaviour)
{
m_Behaviour = behaviour;
}
public void OnGUI() { }
}
- In the same script, replace the
OnGUI
function with the following code:
IAsset m_CurrentAsset;
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.RefreshAssetCollections();
}
GUILayout.BeginVertical();
if (GUILayout.Button("Refresh asset collections"))
{
_ = m_Behaviour.RefreshAssetCollections();
}
GUILayout.Label("Collections:");
if (m_Behaviour.Collections != null)
{
foreach (var collection in m_Behaviour.Collections)
{
DisplayAssetCollections(collection);
}
}
GUILayout.EndVertical();
}
void DisplayAssetCollections(CollectionPath collectionPath)
{
GUILayout.BeginHorizontal();
GUILayout.Label($"{collectionPath}");
if (GUILayout.Button("Remove asset"))
{
_ = m_Behaviour.RemoveAssetFromCollectionAsync(collectionPath);
}
GUILayout.EndHorizontal();
}
- Open the
AssetManagementUI
script you created and replace the content 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 UseCaseAssetMetadataExampleUI(m_Behaviour));
The code snippet displays the following UI elements:
- A list of metadata with Select and Delete UI buttons for each metadata key.
- When you select a metadata key, the UI displays an editable field containing the value and a UI button to Update the metadata value.