Create a gist now

Instantly share code, notes, and snippets.

[Unity] Resourcesロードのパス指定を自動化する
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
// Unity 5.5.0p3
namespace TSKT
{
public class ResourceReferer<T> : ScriptableObject
where T : Object
{
[SerializeField]
string path;
public ResourceLoader<T> Load()
{
return new ResourceLoader<T>(path);
}
[SerializeField]
T asset;
[HideInInspector]
[SerializeField]
string guid;
#if UNITY_EDITOR
void OnValidate()
{
string fullPath = null;
if (asset)
{
fullPath = UnityEditor.AssetDatabase.GetAssetPath(asset);
guid = UnityEditor.AssetDatabase.AssetPathToGUID(fullPath);
}
else if (!string.IsNullOrEmpty(guid))
{
fullPath = UnityEditor.AssetDatabase.GUIDToAssetPath(guid);
}
if (!string.IsNullOrEmpty(fullPath))
{
var i = fullPath.IndexOf("/Resources/");
if (i < 0)
{
UnityEngine.Assertions.Assert.IsTrue(false, "asset has to be in Resources : " + fullPath);
}
else
{
asset = null;
var resourcePath = fullPath.Remove(0, i + "/Resources/".Length);
var dir = System.IO.Path.GetDirectoryName(resourcePath);
var file = System.IO.Path.GetFileNameWithoutExtension(resourcePath);
var newPath = dir + "/" + file;
if (path != newPath)
{
path = newPath;
UnityEditor.EditorUtility.SetDirty(this);
}
}
}
}
#endif
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment