// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.IO;
using UnityEditor;
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.Editor
{
///
/// Extensions for ScriptableObjects
///
public static class ScriptableObjectExtensions
{
///
/// Creates, saves, and then opens a new asset for the target ScriptableObject.
///
/// ScriptableObject you want to create an asset file for.
/// Optional path for the new asset.
/// Optional filename for the new asset.
public static ScriptableObject CreateAsset(this ScriptableObject scriptableObject, string path = null, string fileName = null)
{
var name = string.IsNullOrEmpty(fileName) ? $"{scriptableObject.GetType().Name}" : fileName;
if (string.IsNullOrEmpty(path))
{
path = "Assets";
}
if (Path.GetExtension(path) != string.Empty)
{
var subtractedPath = path.Substring(path.LastIndexOf("/", StringComparison.Ordinal));
path = path.Replace(subtractedPath, string.Empty);
}
if (!Directory.Exists(Path.GetFullPath(path)))
{
Directory.CreateDirectory(Path.GetFullPath(path));
}
string assetPathAndName = AssetDatabase.GenerateUniqueAssetPath($"{path}/{name}.asset");
AssetDatabase.CreateAsset(scriptableObject, assetPathAndName);
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
EditorGUIUtility.PingObject(scriptableObject);
return scriptableObject;
}
///
/// Gets all the scriptable object instances in the project.
///
/// The Type of ScriptableObject you're wanting to find instances of.
/// An Array of instances for the type.
public static T[] GetAllInstances() where T : ScriptableObject
{
// FindAssets uses tags check documentation for more info
string[] guids = AssetDatabase.FindAssets($"t:{typeof(T).Name}");
var instances = new T[guids.Length];
for (int i = 0; i < guids.Length; i++)
{
string path = AssetDatabase.GUIDToAssetPath(guids[i]);
instances[i] = AssetDatabase.LoadAssetAtPath(path);
}
return instances;
}
///
/// Gets all the scriptable object instances in the project.
///
/// The Type of ScriptableObject you're wanting to find instances of.
/// An Array of instances for the type.
public static ScriptableObject[] GetAllInstances(Type assetType)
{
// FindAssets uses tags check documentation for more info
string[] guids = AssetDatabase.FindAssets($"t:{assetType.Name}");
var instances = new ScriptableObject[guids.Length];
for (int i = 0; i < guids.Length; i++)
{
string path = AssetDatabase.GUIDToAssetPath(guids[i]);
instances[i] = AssetDatabase.LoadAssetAtPath(path);
}
return instances;
}
}
}