Use case: Manage field definitions in an organization
You can use the Unity Cloud Assets package to create, delete, and edit the field definitions of an organization.
Organization or Asset Manager Project role | List field definitions | Create/delete/update field definitions |
---|---|---|
Asset Management Viewer |
yes | no |
Asset Management Consumer |
yes | no |
Asset Management Contributor |
yes | no |
Organization Owner |
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 and select the field definitions in an organization
To list the existing field definitions in an Organization, follow these steps:
- Open the
AssetManagementBehaviour
script you created. - Add the following code to the end of the class:
public List<IFieldDefinition> FieldDefinitions { get; set; }
public IFieldDefinition CurrentFieldDefinition { get; private set; }
public FieldDefinitionUpdate FieldDefinitionUpdate { get; private set; }
public async Task GetFieldDefinitions()
{
FieldDefinitions = new List<IFieldDefinition>();
CurrentFieldDefinition = null;
var asyncList = PlatformServices.AssetRepository.QueryFieldDefinitions(CurrentOrganization.Id)
.ExecuteAsync(CancellationToken.None);
await foreach (var fieldDefinition in asyncList)
{
FieldDefinitions.Add(fieldDefinition);
}
}
public void SetCurrentFieldDefinition(IFieldDefinition fieldDefinition)
{
CurrentFieldDefinition = fieldDefinition;
FieldDefinitionUpdate = CurrentFieldDefinition != null ? new FieldDefinitionUpdate(CurrentFieldDefinition) : null;
}
The code snippet does the following:
- Populates a list of field definition in the selected Organization.
- Holds a reference to the selected field.
- Holds a reference to the object used to update the field.
Create a field definition
To create a field definition, follow these steps:
- Open the
AssetManagementBehaviour
script you created. - Add the following code to the end of the class:
public async Task CreateFieldDefinitionAsync(IFieldDefinitionCreation fieldDefinitionCreation, CancellationToken cancellationToken)
{
await PlatformServices.AssetRepository.CreateFieldDefinitionAsync(CurrentOrganization.Id, fieldDefinitionCreation, cancellationToken);
FieldDefinitions = null;
Debug.Log($"Field definition {fieldDefinitionCreation.Key} created.");
}
The code snippet does the following:
- Creates a new field definition given an
IFieldDefinitionCreation
object. - Prints a message to the console on success.
Update a field definition
To update a field definition, follow these steps:
- Open the
AssetManagementBehaviour
script you created. - Add the following code to the end of the class:
public async Task UpdateFieldDefinition(IEnumerable<string> selectionAcceptedValues)
{
await CurrentFieldDefinition.UpdateAsync(FieldDefinitionUpdate, CancellationToken.None);
if (CurrentFieldDefinition.Type == FieldDefinitionType.Selection)
{
await CurrentFieldDefinition.AsSelectionFieldDefinition().SetSelectionValuesAsync(selectionAcceptedValues, CancellationToken.None);
}
Debug.Log($"Field definition {CurrentFieldDefinition.Descriptor.FieldKey} updated.");
}
The code snippet does the following:
- Updates the selected field definition.
- Prints a message to the console on success.
Delete a field definition
To delete a field definition, follow these steps:
- Open the
AssetManagementBehaviour
script you created. - Add the following code to the end of the class:
public async Task DeleteFieldDefinition(IFieldDefinition fieldDefinition)
{
await PlatformServices.AssetRepository.DeleteFieldDefinitionAsync(fieldDefinition.Descriptor, CancellationToken.None);
FieldDefinitions = null;
if (fieldDefinition == CurrentFieldDefinition)
{
SetCurrentFieldDefinition(null);
}
Debug.Log($"Field definition {fieldDefinition.Descriptor.FieldKey} deleted.");
}
The code snippet does the following:
- Deletes the field definition passed as a parameter.
- Refreshes the list of field definition for the Organization.
- If the deleted field definition was the currently selected one, it sets the current selection to
null
. - Prints a message to the console on success.
Add the UI for listing and managing field definitions
To create UI for listing and managing field definitions, 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
UseCaseManageFieldDefinitionsExampleUI
. - Open the
UseCaseManageFieldDefinitionsExampleUI
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.Identity;
using UnityEngine;
public class UseCaseManageFieldDefinitionsExampleUI : IAssetManagementUI
{
readonly AssetManagementBehaviour m_Behaviour;
readonly string[] m_FieldTypeList;
GUIStyle m_ErrorLabelStyle;
public UseCaseManageFieldDefinitionsExampleUI(AssetManagementBehaviour behaviour)
{
m_Behaviour = behaviour;
m_FieldTypeList = Enum.GetNames(typeof(FieldDefinitionType));
}
public void OnGUI() { }
}
- In the same script, replace the
OnGUI
function with the following code:
IOrganization m_CurrentOrganization;
FieldDefinitionCreation m_FieldDefinitionCreation = new();
List<string> m_SelectionAcceptedValues = new();
Vector2 m_FieldsScrollPosition;
public void OnGUI()
{
if (m_ErrorLabelStyle == null)
{
m_ErrorLabelStyle = new GUIStyle(GUI.skin.label) {normal = {textColor = Color.red}};
}
if (!m_Behaviour.IsOrganizationSelected) return;
if (m_CurrentOrganization != m_Behaviour.CurrentOrganization)
{
m_CurrentOrganization = m_Behaviour.CurrentOrganization;
m_Behaviour.SetCurrentFieldDefinition(null);
m_Behaviour.FieldDefinitions = null;
}
GUILayout.BeginVertical();
// Go back to select a different scene.
if (GUILayout.Button("Back"))
{
m_Behaviour.SetSelectedOrganization(null);
return;
}
if (GUILayout.Button("Refresh", GUILayout.Width(60)) || m_Behaviour.FieldDefinitions == null)
{
_ = m_Behaviour.GetFieldDefinitions();
}
GUILayout.EndVertical();
GUILayout.BeginVertical();
if (GUILayout.Button("Create New"))
{
m_Behaviour.SetCurrentFieldDefinition(null);
m_FieldDefinitionCreation = new FieldDefinitionCreation();
}
GUILayout.Label("Fields:");
ListFieldDefinitions(m_Behaviour.FieldDefinitions?.ToArray() ?? Array.Empty<IFieldDefinition>());
GUILayout.EndVertical();
GUILayout.BeginVertical();
if (m_Behaviour.CurrentFieldDefinition == null)
{
CreateFieldDefinition();
}
else
{
DisplayFieldDefinition();
}
GUILayout.EndVertical();
}
void ListFieldDefinitions(IReadOnlyList<IFieldDefinition> fields)
{
if (fields.Count == 0)
{
GUILayout.Label(" ! No fields !");
}
else
{
m_FieldsScrollPosition = GUILayout.BeginScrollView(m_FieldsScrollPosition, GUILayout.MinWidth(Screen.width * 0.2f), GUILayout.Height(Screen.height * 0.8f));
for (var i = 0; i < fields.Count; ++i)
{
GUILayout.BeginHorizontal();
GUILayout.Label(fields[i].Descriptor.FieldKey);
if (GUILayout.Button("Select", GUILayout.Width(60)))
{
m_Behaviour.SetCurrentFieldDefinition(fields[i]);
if (m_Behaviour.CurrentFieldDefinition.Type == FieldDefinitionType.Selection)
{
m_SelectionAcceptedValues = fields[i].AsSelectionFieldDefinition().AcceptedValues?.ToList() ?? new List<string>();
}
}
if (GUILayout.Button("Delete"))
{
_ = m_Behaviour.DeleteFieldDefinition(fields[i]);
}
GUILayout.EndHorizontal();
}
GUILayout.EndScrollView();
}
}
void CreateFieldDefinition()
{
GUILayout.Label("New Field Definition (* = required):");
GUILayout.Label("Field Key *:");
m_FieldDefinitionCreation.Key = GUILayout.TextField(m_FieldDefinitionCreation.Key).Trim();
GUILayout.Label("Display Name:");
m_FieldDefinitionCreation.DisplayName = GUILayout.TextField(m_FieldDefinitionCreation.DisplayName);
GUILayout.Label("Type *:");
var type = (int) m_FieldDefinitionCreation.Type;
type = GUILayout.SelectionGrid(type, m_FieldTypeList, 3);
m_FieldDefinitionCreation.Type = Enum.Parse<FieldDefinitionType>(m_FieldTypeList[type], true);
var isEmpty = string.IsNullOrEmpty(m_FieldDefinitionCreation.Key);
var isUnique = m_Behaviour.FieldDefinitions != null && m_Behaviour.FieldDefinitions.All(x => x.Descriptor.FieldKey != m_FieldDefinitionCreation.Key);
var canCreate = !isEmpty && isUnique;
GUI.enabled = canCreate;
if (GUILayout.Button("Create"))
{
_ = m_Behaviour.CreateFieldDefinitionAsync(m_FieldDefinitionCreation, CancellationToken.None);
m_FieldDefinitionCreation = new FieldDefinitionCreation();
}
if (!isEmpty && !isUnique)
{
GUILayout.Label($"Field {m_FieldDefinitionCreation.Key} already exists.", m_ErrorLabelStyle);
}
GUI.enabled = true;
}
void DisplayFieldDefinition()
{
var field = m_Behaviour.CurrentFieldDefinition;
GUILayout.Label($"Field Definition: {field.Descriptor.FieldKey}");
GUILayout.Label($"Is deleted: {field.IsDeleted}");
GUILayout.Label($"Created on: {field.AuthoringInfo?.Created:yyyy-M-d dddd}");
GUILayout.Label($"Updated on: {field.AuthoringInfo?.Updated:yyyy-M-d dddd}");
var multiSelectionStatus = string.Empty;
var acceptedValues = string.Empty;
if (field.Type == FieldDefinitionType.Selection)
{
var selectionFieldDefinition = field.AsSelectionFieldDefinition();
multiSelectionStatus = selectionFieldDefinition.Multiselection ? ", Multi" : ", Single";
acceptedValues = string.Join(',', selectionFieldDefinition.AcceptedValues ?? new List<string>());
}
GUILayout.Label($"Type: {field.Type}{multiSelectionStatus}");
if (field.IsDeleted)
{
GUILayout.Label($"Display name: {field.DisplayName}");
if (!string.IsNullOrEmpty(acceptedValues))
{
GUILayout.Label($"Accepted values: {acceptedValues}");
}
return;
}
GUILayout.Space(5f);
DisplayUpdateValues(m_Behaviour.FieldDefinitionUpdate);
if (m_Behaviour.CurrentFieldDefinition.Type == FieldDefinitionType.Selection)
{
DisplaySelectionValues();
}
GUILayout.Space(5f);
if (GUILayout.Button("Update"))
{
_ = m_Behaviour.UpdateFieldDefinition(m_SelectionAcceptedValues);
}
}
static void DisplayUpdateValues(FieldDefinitionUpdate update)
{
GUILayout.Label("Display name:");
update.DisplayName = GUILayout.TextField(update.DisplayName);
}
void DisplaySelectionValues()
{
GUILayout.Space(5f);
GUILayout.Label("Accepted Values:");
var value = string.Join(',', m_SelectionAcceptedValues);
var newValue = GUILayout.TextField(value);
if (value != newValue)
{
m_SelectionAcceptedValues = newValue.Split(',').Select(x => x.Trim()).ToList();
}
}
- 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 UseCaseManageFieldDefinitionsExampleUI(m_Behaviour));
The code snippet does the following:
- Displays a list of the selected Organization's field definitions. Each field definition has a UI button to select it and a UI button to delete it.
- Displays a UI button to create a new field definitions.
- When a field definition is selected, additional UI elements display the field definition's information.