Get started with Asset SDK
Asset Manager is a Unity Cloud service that allows you to manage your assets in the cloud. Use Assets SDK to perform the following:
- Create and read an asset project.
- Create, read, and update:
- assets
- datasets
- files
- Download files.
- Create, read, update, and delete collections.
- Search your assets in an asset project or organization based on a set of criteria.
- Group and count assets based on a set of criteria.
- Link and unlink assets from projects.
- Link and unlink assets from collections.
- Start transformations on datasets.
- Create, read, update and delete the field definitions of an organization.
- Add and remove the accepted values of field definitions of the
Selection
type.
This section explains how to set up a basic scene and script to initialize and use the Unity Assets package with Asset Manager. The script performs a search for all assets of the selected project and displays the results in a GUI.
Before you begin, verify you meet the prerequisites.
Requirements
To use Assets SDK, you must have a minimum role of Asset Manager Viewer in your Unity Cloud project.
Integrate the package in a Unity project
To integrate the Unity Cloud Assets package in a Unity project, do the following:
- Set up a Unity scene
- Create an
AssetManager
- Create the
PlatformServices
- Create the base behavior for managing assets
- Create the behavior for managing assets
- Create the base MonoBehaviour for the UI
- Create an interface for all UI scripts
Set up a Unity scene
To set up a Unity scene, follow these steps:
- In the Project window of the Unity Editor, go to Assets > Scenes.
- Select and hold the
Assets/Scenes
folder. - Go to Create > Scene.
- Name the new scene
AssetManagementExample
.
Create an AssetManager
To create an AssetManager
object, first create a MonoBehaviour
class to manage the UI and then create the AssetManager
object in your scene as follows:
- Create a
MonoBehaviour
class to manage the UI: - Create the
AssetManager
object in your scene:
Create the PlatformServices
To set up the necessary components, follow these steps:
- In the Project window of the Unity Editor, go to Assets > Scripts.
- Select and hold the
Assets/Scripts
folder. - Go to Create > C# Script.
- Name your script
PlatformServices
. - Open the file and replace its contents with the following code sample:
using System;
using System.Threading.Tasks;
using Unity.Cloud.Assets;
using Unity.Cloud.AppLinking.Runtime;
using Unity.Cloud.Common;
using Unity.Cloud.Common.Runtime;
using Unity.Cloud.Identity;
using Unity.Cloud.Identity.Runtime;
public static class PlatformServices
{
/// <summary>
/// Returns a <see cref="ICompositeAuthenticator"/>.
/// </summary>
public static ICompositeAuthenticator Authenticator { get; private set; }
/// <summary>
/// Returns a <see cref="IAuthenticationStateProvider"/>.
/// </summary>
public static IAuthenticationStateProvider AuthenticationStateProvider => Authenticator;
/// <summary>
/// Returns an <see cref="IOrganizationRepository"/>.
/// </summary>
public static IOrganizationRepository OrganizationRepository => Authenticator;
/// <summary>
/// Returns an <see cref="IAssetRepository"/>.
/// </summary>
public static IAssetRepository AssetRepository { get; private set; }
public static void Create()
{
var playerSettings = UnityCloudPlayerSettings.Instance;
var serviceConnector = ServiceConnectorFactory.Create(
PlatformSupportFactory.GetAuthenticationPlatformSupport(),
new UnityHttpClient(),
playerSettings,
playerSettings);
Authenticator = serviceConnector.CompositeAuthenticator;
AssetRepository = AssetRepositoryFactory.Create(serviceConnector.ServiceHttpClient, serviceConnector.ServiceHostResolver);
}
/// <summary>
/// A Task that initializes all platform services.
/// </summary>
/// <returns>A Task.</returns>
public static async Task InitializeAsync()
{
await Authenticator.InitializeAsync();
}
/// <summary>
/// Shuts down all platform services.
/// </summary>
public static void ShutDownServices()
{
(Authenticator as IDisposable)?.Dispose();
Authenticator = null;
}
}
This script does the following:
- Initializes an
ICompositeAuthenticator
interface for signing in and verifying your identity when you access the HTTP services. - Initializes an
IOrganizationRepository
interface to fetch your organizations. - Initializes an
IAssetRepository
interface to interact with the Asset Manager service.
To initialize the PlatformServices
class in your scene, follow these steps:
- In the Project window of the Unity Editor, go to Assets > Scripts.
- Select and hold the
Assets/Scripts
folder. - Go to Create > C# Script.
- Name your script
PlatformServicesInitialization
. - In the
AssetManagementExample
scene that you created here, select and hold the hierarchy and select Create Empty. - Name your new object
PlatformServices
. - Select the
PlatformServices
object and add thePlatformServicesInitialization
script that you created here. - Update the
PlatformServicesInitialization
class in yourPlatformServicesInitialization.cs
file as shown below:
using System.Threading.Tasks;
using UnityEngine;
/// <summary>
/// A Mono behaviour class to initialize services and dependencies for the Unity Cloud platform.
/// </summary>
[DefaultExecutionOrder(int.MinValue)]
public class PlatformServicesInitialization : MonoBehaviour
{
void Awake()
{
DontDestroyOnLoad(gameObject);
PlatformServices.Create();
}
async Task Start()
{
await PlatformServices.InitializeAsync();
}
}
This script does the following:
- Triggers the creation of the services available in the
PlatformServices
class. - Initializes the
ICompositeAuthenticator
interface.
To clean up the PlatformServices
class in your scene, follow these steps:
- In the Project window of the Unity Editor, go to Assets > Scripts.
- Select and hold the
Assets/Scripts
folder. - Go to Create > C# Script.
- Name your script
PlatformServicesShutdown
. - Select the
PlatformServices
object that you created here and add thePlatformServicesShutdown
script that you created in the previous step. - Update the
PlatformServicesShutdown
class in yourPlatformServicesShutdown.cs
file as shown below:
using UnityEngine;
/// <summary>
/// A Mono behaviour class to shut down services and dependencies from the Unity Cloud platform.
/// </summary>
[DefaultExecutionOrder(int.MaxValue)]
public class PlatformServicesShutdown : MonoBehaviour
{
void OnDestroy()
{
PlatformServices.ShutDownServices();
}
}
This script cleans up of the services when the scene is closed.
Note
Read more about the platform services pattern implementation in the Identity package documentation.
Create the base behavior for managing assets
To create the base behavior for asset management, follow these steps:
- In the Project window of the Unity Editor, go to Assets > Scripts.
- Select and hold the
Assets/Scripts
folder. - Go to Create > C# Script.
- Name your script
BaseAssetBehaviour
. - Open the file and replace its contents with the following code sample:
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Unity.Cloud.Assets;
using Unity.Cloud.Common;
using UnityEngine;
public abstract class BaseAssetBehaviour
{
internal class LogProgress : IProgress<HttpProgress>
{
string m_Id;
public LogProgress(string id)
{
m_Id = id;
}
public void Report(HttpProgress value)
{
if (value.UploadProgress.HasValue)
{
Debug.Log($"Upload progress for {m_Id}: {value.UploadProgress * 100} %");
}
if (value.DownloadProgress.HasValue)
{
Debug.Log($"Download progress for {m_Id}: {value.DownloadProgress * 100} %");
}
}
}
CancellationTokenSource m_AssetCancellationTokenSrc = new();
Dictionary<AssetId, List<AssetVersion>> m_AssetVersions = new();
Dictionary<AssetVersion, AssetProperties> m_AssetProperties { get; } = new();
public abstract bool CanSelectAsset { get; }
public List<IAsset> AvailableAssets { get; } = new();
public int AssetCount { get; protected set; }
public IAsset CurrentAsset { get; set; }
public virtual void Clear()
{
m_AssetCancellationTokenSrc.Cancel();
m_AssetCancellationTokenSrc.Dispose();
CurrentAsset = null;
}
public abstract void ClearParentSelection();
public async Task GetAssetsAsync(AssetQueryBuilder assetQueryBuilder, AssetDescriptor? selectedAsset = null)
{
m_AssetCancellationTokenSrc.Cancel();
m_AssetCancellationTokenSrc.Dispose();
m_AssetCancellationTokenSrc = new CancellationTokenSource();
try
{
var token = m_AssetCancellationTokenSrc.Token;
var assets = assetQueryBuilder.ExecuteAsync(token);
AvailableAssets.Clear();
m_AssetVersions.Clear();
m_AssetProperties.Clear();
CurrentAsset = null;
await foreach (var asset in assets)
{
AvailableAssets.Add(asset);
if (asset.Descriptor == selectedAsset)
{
CurrentAsset = asset;
}
IncludeAssetVersion(asset.Descriptor);
var properties = await asset.GetPropertiesAsync(token);
m_AssetProperties[asset.Descriptor.AssetVersion] = properties;
}
}
catch (OperationCanceledException oe)
{
Debug.Log(oe);
}
catch (AggregateException e)
{
Debug.LogError(e.InnerException);
}
catch (Exception e)
{
Debug.LogError(e);
}
}
public bool TryGetAssetProperties(AssetVersion assetVersion, out AssetProperties properties) => m_AssetProperties.TryGetValue(assetVersion, out properties);
public bool TryGetAssetProperties(AssetId assetId, out AssetProperties properties)
{
if (m_AssetVersions.TryGetValue(assetId, out var versions) && versions.Count > 0)
{
return TryGetAssetProperties(versions[0], out properties);
}
properties = default;
return false;
}
public void IncludeProperties(AssetDescriptor assetDescriptor, AssetProperties properties)
{
IncludeAssetVersion(assetDescriptor);
m_AssetProperties[assetDescriptor.AssetVersion] = properties;
}
void IncludeAssetVersion(AssetDescriptor assetDescriptor)
{
if (!m_AssetVersions.TryGetValue(assetDescriptor.AssetId, out var versions))
{
versions = new List<AssetVersion>();
m_AssetVersions[assetDescriptor.AssetId] = versions;
}
versions.Add(assetDescriptor.AssetVersion);
}
}
This script does the following:
- Performs a search to list the assets based on the provided query.
Create the behavior for managing assets
To create the behavior for managing assets, follow these steps:
- In the Project window of the Unity Editor, go to Assets > Scripts.
- Select and hold the
Assets/Scripts
folder. - Go to Create > C# Script.
- Name your script
AssetManagementBehaviour
. - Open the file and replace its contents with the following code sample:
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Unity.Cloud.Assets;
using Unity.Cloud.Common;
using Unity.Cloud.Identity;
using UnityEngine;
public class AssetManagementBehaviour : BaseAssetBehaviour
{
IOrganization[] m_AvailableOrganizations;
CancellationTokenSource m_ProjectCancellationTokenSrc = new();
public override bool CanSelectAsset => IsProjectSelected;
public IOrganization[] AvailableOrganizations => m_AvailableOrganizations;
public IOrganization CurrentOrganization { get; private set; }
public bool IsOrganizationSelected => CurrentOrganization != null;
public List<IAssetProject> AvailableProjects { get; } = new();
public IAssetProject CurrentProject { get; private set; }
public bool IsProjectSelected => CurrentProject != null;
readonly Dictionary<ProjectId, string> m_ProjectNames = new();
public override void Clear()
{
base.Clear();
m_ProjectCancellationTokenSrc.Cancel();
m_ProjectCancellationTokenSrc.Dispose();
CurrentProject = null;
m_ProjectNames.Clear();
AvailableProjects.Clear();
CurrentOrganization = null;
}
public override void ClearParentSelection()
{
SetSelectedProject(null);
}
public void SetSelectedOrganization(IOrganization organization)
{
CurrentAsset = null;
CurrentProject = null;
CurrentOrganization = organization;
if (CurrentOrganization != null)
{
_ = GetProjectsAsync();
}
}
public void SetSelectedProject(IAssetProject project)
{
CurrentAsset = null;
CurrentProject = project;
if (CurrentProject != null)
{
Debug.Log($"Selected project: {GetProjectName(CurrentProject.Descriptor.ProjectId)}");
_ = GetAssetCount(CurrentProject);
_ = GetAssetsAsync(CurrentProject.QueryAssets());
}
}
public async Task GetOrganizationsAsync()
{
m_AvailableOrganizations = null;
try
{
var organizations = new List<IOrganization>();
var organizationsAsyncEnumerable = PlatformServices.OrganizationRepository.ListOrganizationsAsync(Range.All);
await foreach (var organization in organizationsAsyncEnumerable)
{
organizations.Add(organization);
}
m_AvailableOrganizations = organizations.ToArray();
}
catch (OperationCanceledException oe)
{
Debug.Log(oe);
}
catch (AggregateException e)
{
Debug.LogError(e.InnerException);
}
catch (Exception e)
{
Debug.LogError(e);
}
}
public async Task GetProjectsAsync()
{
m_ProjectCancellationTokenSrc.Cancel();
m_ProjectCancellationTokenSrc.Dispose();
m_ProjectCancellationTokenSrc = new CancellationTokenSource();
try
{
var token = m_ProjectCancellationTokenSrc.Token;
var projects = PlatformServices.AssetRepository.ListAssetProjectsAsync(CurrentOrganization.Id, Range.All, token);
AvailableProjects.Clear();
CurrentProject = null;
await foreach (var project in projects)
{
AvailableProjects.Add(project);
var properties = await project.GetPropertiesAsync(token);
m_ProjectNames[project.Descriptor.ProjectId] = properties.Name;
}
}
catch (OperationCanceledException oe)
{
Debug.Log(oe);
}
catch (AggregateException e)
{
Debug.LogError(e.InnerException);
}
catch (Exception e)
{
Debug.LogError(e);
}
}
public string GetProjectName(ProjectId projectId)
{
return m_ProjectNames.TryGetValue(projectId, out var name) ? name : projectId.ToString();
}
async Task GetAssetCount(IAssetProject assetProject)
{
AssetCount = await assetProject.CountAssetsAsync(CancellationToken.None);
}
}
This script does the following:
- Inherits from the
BaseAssetBehaviour
class that you created here. - Provides the functions to list and select organizations.
- Provides the functions to list and select projects.
Create the base MonoBehaviour for the UI
To create the MonoBehaviour
for the UI, follow these steps:
- In the Project window of the Unity Editor, go to Assets > Scripts.
- Select and hold the
Assets/Scripts
folder. - Go to Create > C# Script.
- Name your script
BaseAssetUI
. - Open the file and replace its contents with the following code sample:
using System;
using System.Collections.Generic;
using Unity.Cloud.Identity;
using UnityEngine;
public abstract class BaseAssetUI<T> : MonoBehaviour where T : BaseAssetBehaviour, new()
{
protected readonly T m_Behaviour = new();
protected readonly List<IAssetManagementUI> m_UI = new();
Vector2 m_ScreenScrollerPosition = Vector2.zero;
IAuthenticationStateProvider m_AuthenticationStateProvider;
bool IsLoggedIn => m_AuthenticationStateProvider?.AuthenticationState == AuthenticationState.LoggedIn;
void Start()
{
m_AuthenticationStateProvider = PlatformServices.AuthenticationStateProvider;
m_AuthenticationStateProvider.AuthenticationStateChanged += OnAuthenticationStateChanged;
}
void OnDestroy()
{
if (m_AuthenticationStateProvider != null)
{
m_AuthenticationStateProvider.AuthenticationStateChanged -= OnAuthenticationStateChanged;
}
m_Behaviour.Clear();
}
void OnGUI()
{
m_ScreenScrollerPosition = GUILayout.BeginScrollView(m_ScreenScrollerPosition);
GUILayout.BeginHorizontal(GUILayout.Width(Screen.width - 18f), GUILayout.Height(Screen.height - 18f));
UpdateAuthenticationUI(m_AuthenticationStateProvider.AuthenticationState);
if (!IsLoggedIn)
{
GUILayout.EndHorizontal();
GUILayout.EndScrollView();
return;
}
foreach (var ui in m_UI)
{
ui.OnGUI();
}
AdditionalGUI();
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
GUILayout.EndScrollView();
}
protected virtual void AdditionalGUI()
{
// Do more stuff here.
}
static void UpdateAuthenticationUI(AuthenticationState state)
{
GUILayout.BeginVertical();
switch (state)
{
case AuthenticationState.AwaitingInitialization:
GUILayout.Label("Initializing Service...");
break;
case AuthenticationState.AwaitingLogout:
GUILayout.Label("Logging out...");
break;
case AuthenticationState.LoggedOut:
if (GUILayout.Button("Login"))
{
_ = PlatformServices.Authenticator.LoginAsync();
}
break;
case AuthenticationState.AwaitingLogin:
GUILayout.Label("Logging in...");
if (GUILayout.Button("Cancel"))
{
PlatformServices.Authenticator.CancelLogin();
}
break;
case AuthenticationState.LoggedIn:
if (GUILayout.Button("Logout"))
{
_ = PlatformServices.Authenticator.LogoutAsync();
}
break;
default:
throw new ArgumentOutOfRangeException(nameof(state), state, null);
}
GUILayout.EndVertical();
}
protected abstract void OnAuthenticationStateChanged(AuthenticationState obj);
}
Create an interface for all UI scripts
To create the interface for all UI scripts, follow these steps:
- In the Project window of the Unity Editor, go to Assets > Scripts.
- Select and hold the
Assets/Scripts
folder. - Go to Create > C# Script.
- Name your script
IAssetManagementUI
. - Open the file and replace its contents with the following code sample:
public interface IAssetManagementUI
{
public void OnGUI();
}
How do I...?
Select an organization
To create a UI for selecting an organization, do the following:
- In the Project window of the Unity Editor, go to Assets > Scripts.
- Select and hold the
Assets/Scripts
folder. - Go to Create > C# Script.
- Name your script
OrganizationSelectionExampleUI
. - Open the file and replace its contents with the following code sample:
using System;
using UnityEngine;
public class OrganizationSelectionExampleUI : IAssetManagementUI
{
readonly AssetManagementBehaviour m_Behaviour;
Vector2 m_OrganizationListScrollPosition;
public OrganizationSelectionExampleUI(AssetManagementBehaviour behaviour)
{
m_Behaviour = behaviour;
}
public void OnGUI()
{
if (m_Behaviour.IsOrganizationSelected) return;
// Refresh the org list
if (GUILayout.Button("Refresh", GUILayout.Width(60)))
{
_ = m_Behaviour.GetOrganizationsAsync();
return;
}
GUILayout.Space(15f);
// If an organization is not selected, list those available.
SelectAnOrganization();
}
void SelectAnOrganization()
{
GUILayout.BeginVertical();
GUILayout.Label("Available Organizations:");
GUILayout.Space(5f);
var availableOrganizations = m_Behaviour.AvailableOrganizations;
if (availableOrganizations != null)
{
m_OrganizationListScrollPosition = GUILayout.BeginScrollView(m_OrganizationListScrollPosition, GUILayout.ExpandHeight(true), GUILayout.Width(250));
for (var i = 0; i < availableOrganizations.Length; ++i)
{
if (GUILayout.Button(availableOrganizations[i].Name))
{
m_Behaviour.SetSelectedOrganization(availableOrganizations[i]);
}
}
GUILayout.EndScrollView();
}
else
{
GUILayout.Label("Loading...");
}
GUILayout.EndVertical();
}
}
This script generates a UI to list and select organizations.
Select a project
To create a UI for selecting a project, do the following:
- In the Project window of the Unity Editor, go to Assets > Scripts.
- Select and hold the
Assets/Scripts
folder. - Go to Create > C# Script.
- Name your script
ProjectSelectionExampleUI
. - Open the file and replace its contents with the following code sample:
using System;
using UnityEngine;
public class ProjectSelectionExampleUI : IAssetManagementUI
{
readonly AssetManagementBehaviour m_Behaviour;
Vector2 m_ProjectListScrollPosition;
public ProjectSelectionExampleUI(AssetManagementBehaviour behaviour)
{
m_Behaviour = behaviour;
}
public void OnGUI()
{
if (!m_Behaviour.IsOrganizationSelected || m_Behaviour.IsProjectSelected) return;
GUILayout.BeginVertical();
// Go back to select a different scene.
if (GUILayout.Button("Back"))
{
m_Behaviour.SetSelectedOrganization(null);
return;
}
// Refresh the project list
if (GUILayout.Button("Refresh", GUILayout.Width(60)))
{
_ = m_Behaviour.GetProjectsAsync();
return;
}
GUILayout.EndVertical();
GUILayout.Space(15f);
SelectAProject();
}
void SelectAProject()
{
GUILayout.BeginVertical();
GUILayout.Label($"{m_Behaviour.CurrentOrganization.Name}");
GUILayout.Space(15f);
GUILayout.Label("Available Projects:");
GUILayout.Space(5f);
var projects = m_Behaviour.AvailableProjects.ToArray();
if (projects.Length > 0)
{
m_ProjectListScrollPosition = GUILayout.BeginScrollView(m_ProjectListScrollPosition, GUILayout.ExpandHeight(true), GUILayout.Width(250));
for (var i = 0; i < projects.Length; ++i)
{
var projectId = projects[i].Descriptor.ProjectId;
GUI.enabled = projectId != m_Behaviour.CurrentProject?.Descriptor.ProjectId;
if (GUILayout.Button(m_Behaviour.GetProjectName(projectId)))
{
m_Behaviour.SetSelectedProject(projects[i]);
}
GUI.enabled = true;
}
GUILayout.EndScrollView();
}
else
{
GUILayout.Label("No projects found.");
}
GUILayout.EndVertical();
}
}
This script generates a UI to list and select projects.
Select an asset
To create a UI for selecting an asset, do the following:
- In the Project window of the Unity Editor, go to Assets > Scripts.
- Select and hold the
Assets/Scripts
folder. - Go to Create > C# Script.
- Name your script
AssetSelectionExampleUI
. - Open the file and replace its contents with the following code sample:
using System;
using UnityEngine;
public class AssetSelectionExampleUI : IAssetManagementUI
{
readonly BaseAssetBehaviour m_Behaviour;
Vector2 m_ListScrollPosition;
public AssetSelectionExampleUI(BaseAssetBehaviour behaviour)
{
m_Behaviour = behaviour;
}
public void OnGUI()
{
if (!m_Behaviour.CanSelectAsset) return;
GUILayout.BeginVertical();
if (GUILayout.Button("Back"))
{
m_Behaviour.ClearParentSelection();
return;
}
GUILayout.Space(15f);
ListAssets();
GUILayout.EndVertical();
}
void ListAssets()
{
GUILayout.Label($"Available Assets ({m_Behaviour.AssetCount}):");
GUILayout.Space(5f);
var assets = m_Behaviour.AvailableAssets.ToArray();
if (assets.Length > 0)
{
m_ListScrollPosition = GUILayout.BeginScrollView(m_ListScrollPosition, GUILayout.ExpandHeight(true), GUILayout.Width(250));
for (var i = 0; i < assets.Length; ++i)
{
GUILayout.BeginHorizontal();
var name = m_Behaviour.TryGetAssetProperties(assets[i].Descriptor.AssetVersion, out var properties) ? properties.Name : assets[i].Descriptor.AssetId.ToString();
GUILayout.Label(name, GUILayout.Width(150));
GUI.enabled = assets[i].Descriptor.AssetId != m_Behaviour.CurrentAsset?.Descriptor.AssetId;
if (GUILayout.Button("Select", GUILayout.Width(60)))
{
_ = m_Behaviour.CurrentAsset = assets[i];
}
GUILayout.EndHorizontal();
GUI.enabled = true;
}
GUILayout.EndScrollView();
}
else
{
GUILayout.Label("No assets found.");
}
}
}
This script generates a UI to view the selected asset's details.
View an asset
To create a UI for viewing an asset's details, do the following:
- In the Project window of the Unity Editor, go to Assets > Scripts.
- Select and hold the
Assets/Scripts
folder. - Go to Create > C# Script.
- Name your script
UseCaseViewAssetExampleUI
. - Open the file and replace its contents with the following code sample:
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using Unity.Cloud.Assets;
using Unity.Cloud.Common;
public class UseCaseViewAssetExampleUI : IAssetManagementUI
{
readonly BaseAssetBehaviour m_Behaviour;
public UseCaseViewAssetExampleUI(BaseAssetBehaviour behaviour)
{
m_Behaviour = behaviour;
}
public void OnGUI()
{
if (m_Behaviour.CurrentAsset == null) return;
GUILayout.Space(15f);
if (!m_Behaviour.TryGetAssetProperties(m_Behaviour.CurrentAsset.Descriptor.AssetVersion, out var properties))
{
GUILayout.Label(" ! Asset properties not loaded !");
return;
}
GUILayout.BeginVertical();
DisplayAsset(m_Behaviour.CurrentAsset.Descriptor, properties);
GUILayout.EndVertical();
}
static void DisplayAsset(AssetDescriptor descriptor, AssetProperties assetProperties)
{
GUILayout.Label("Id: " + descriptor.AssetId);
GUILayout.Label("Version: " + descriptor.AssetVersion);
GUILayout.Label("Asset properties:");
GUILayout.Space(5f);
GUILayout.Label($"Name: {assetProperties.Name}");
GUILayout.Label($"Type: {assetProperties.Type}");
GUILayout.Label($"Tags: {assetProperties.Tags?.ToList() ?? new List<string>()}");
GUILayout.Space(5f);
GUILayout.Label("Sequence Number: " + assetProperties.FrozenSequenceNumber);
GUILayout.Label("Parent Sequence Number: " + assetProperties.ParentFrozenSequenceNumber);
GUILayout.Space(5f);
if (assetProperties.PreviewFileDescriptor.HasValue)
{
GUILayout.Label("Preview Dataset Id: " + assetProperties.PreviewFileDescriptor.Value.DatasetId);
GUILayout.Label($"Preview File Path: {assetProperties.PreviewFileDescriptor.Value.Path}");
}
else
{
GUILayout.Label("No preview file.");
}
GUILayout.Space(5f);
GUILayout.Label($"Description: {assetProperties.Description}");
}
}
This script generates a UI to list and select assets.
Create an asset
To create an asset, follow these steps:
- Open the
AssetManagementBehaviour
script that you created here. - Add the following code to the end of the class:
public List<IStatusFlow> AvailableStatusFlows { get; private set; }
public async Task GetOrganizationStatusFlows()
{
AvailableStatusFlows = null;
try
{
var statusFlowsAsync = PlatformServices.AssetRepository.ListStatusFlowsAsync(CurrentOrganization.Id, Range.All, CancellationToken.None);
AvailableStatusFlows = new List<IStatusFlow>();
await foreach (var statusFlow in statusFlowsAsync)
{
AvailableStatusFlows.Add(statusFlow);
}
}
catch (Exception e)
{
Debug.LogError($"Failed to get organization status flows. {e}");
throw;
}
}
public async Task CreateAssetAsync(AssetType assetType, string statusFlowId)
{
var assetCreation = new AssetCreation("GrayTexture_0")
{
Description = "Documentation example asset creation.",
Type = assetType,
StatusFlowDescriptor = string.IsNullOrEmpty(statusFlowId) ? null : new StatusFlowDescriptor(CurrentOrganization.Id, statusFlowId)
};
try
{
var assetDescriptor = await CurrentProject.CreateAssetLiteAsync(assetCreation, CancellationToken.None);
await GetAssetsAsync(assetDescriptor);
}
catch (Exception e)
{
Debug.LogError($"Failed to create asset. {e}");
throw;
}
}
This code snippet does the following:
- Provides a method to fetch the status flows of the selected organization.
- Provides a method to create a new asset with a type and a status flow.
To create a UI for asset creation, follow these steps:
- In the Project window of the Unity Editor, go to Assets > Scripts.
- Select and hold the
Assets/Scripts
folder. - Go to Create > C# Script.
- Name your script
UseCaseCreateAssetExampleUI
. - Open the file and replace its contents with the following code sample:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using UnityEngine;
using Unity.Cloud.Assets;
using Unity.Cloud.Common;
using Unity.Cloud.Identity;
public class UseCaseCreateAssetExampleUI : IAssetManagementUI
{
readonly AssetManagementBehaviour m_Behaviour;
readonly string[] m_AssetTypeList;
public UseCaseCreateAssetExampleUI(AssetManagementBehaviour behaviour)
{
m_Behaviour = behaviour;
m_AssetTypeList = AssetTypeExtensions.AssetTypeList().ToArray();
}
public void OnGUI() { }
}
- In the same script, replace the
OnGUI
function with the following code:
OrganizationId m_OrganizationId;
AssetType m_SelectedType = AssetType.Other;
int m_SelectedStatusFlow;
public void OnGUI()
{
if (!m_Behaviour.IsProjectSelected) return;
if (m_OrganizationId != m_Behaviour.CurrentOrganization.Id)
{
m_OrganizationId = m_Behaviour.CurrentOrganization.Id;
_ = m_Behaviour.GetOrganizationStatusFlows();
}
GUILayout.BeginVertical();
GUILayout.BeginHorizontal();
GUILayout.Label("Type");
var type = (int) m_SelectedType;
type = GUILayout.SelectionGrid(type, m_AssetTypeList, 3, GUILayout.ExpandWidth(true));
if (type != -1)
m_SelectedType = (AssetType) type;
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.Label("Status Flow");
if (m_Behaviour.AvailableStatusFlows == null)
{
GUILayout.Label("Loading...");
}
else
{
var statusFlowNames = m_Behaviour.AvailableStatusFlows.Select(x => x.Name).ToArray();
m_SelectedStatusFlow = GUILayout.SelectionGrid(m_SelectedStatusFlow, statusFlowNames, 3, GUILayout.ExpandWidth(true));
}
GUILayout.EndHorizontal();
if (GUILayout.Button("Create", GUILayout.Width(60)))
{
var statusFlowId = string.Empty;
if (m_Behaviour.AvailableStatusFlows != null && m_SelectedStatusFlow >= 0 && m_SelectedStatusFlow < m_Behaviour.AvailableStatusFlows.Count)
{
statusFlowId = m_Behaviour.AvailableStatusFlows[m_SelectedStatusFlow].Descriptor.StatusFlowId;
}
_ = m_Behaviour.CreateAssetAsync(m_SelectedType, statusFlowId);
}
GUILayout.EndVertical();
}
Integrate the UI scripts
To bring all your UI scripts into a single MonoBehaviour
, open the AssetManagementUI
script that you created here and replace the contents of the file with the following code sample:
using System;
using Unity.Cloud.Identity;
using UnityEngine;
public class AssetManagementUI : BaseAssetUI<AssetManagementBehaviour>
{
protected virtual void Awake()
{
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 UseCaseCreateAssetExampleUI(m_Behaviour));
m_UI.Add(new UseCaseViewAssetExampleUI(m_Behaviour));
}
protected override void OnAuthenticationStateChanged(AuthenticationState obj)
{
if (obj == AuthenticationState.LoggedIn)
{
_ = m_Behaviour.GetOrganizationsAsync();
}
}
}
This script does the following:
- Inherits from the
BaseAssetUI
class that you created here. - Registers to the
ICompositeAuthenticator
interface to track sign-in changes. - Creates an instance of the
AssetManagementBehaviour
script. - Creates instances of the UI scripts for selecting an organization, project, and asset.
Going further
Read more about asset management.
Updating assets
Read more about updating assets.
Uploading files
Read more about uploading files.
Grouping assets in collections
Use collections to group assets within a project. Read more about managing collections.