Skip to content

Instantly share code, notes, and snippets.

@RDeluxe
Last active August 13, 2018 13:13
Show Gist options
  • Save RDeluxe/0ff5a70ae4358ef70b1c7dc905189753 to your computer and use it in GitHub Desktop.
Save RDeluxe/0ff5a70ae4358ef70b1c7dc905189753 to your computer and use it in GitHub Desktop.
Example of AssetBundle object reference
using System;
using System.IO;
using System.Threading.Tasks;
using Sirenix.OdinInspector;
using UnityEditor;
using UnityEngine;
using Object = UnityEngine.Object;
public class AssetBundleObjectReference<T> where T : Object {
#if UNITY_EDITOR
private T _assetReference;
[AssetsOnly]
[PreviewField]
[ShowInInspector]
public T AssetReference {
get {
if (string.IsNullOrEmpty(_assetGuid)) {
AssetReference = null;
return _assetReference;
}
if (_assetReference == null) {
// Load from AssetDatabase based on _assetGuid
_assetReference =
AssetDatabase.LoadAssetAtPath<T>(AssetDatabase.GUIDToAssetPath(_assetGuid));
}
if (!Application.isPlaying) Setter(); // Update name and path
return _assetReference;
}
set {
if (_assetReference == value) return;
_assetReference = value;
Setter();
}
}
private void Setter() {
if (_assetReference != null) {
var assetPath = AssetDatabase.GetAssetPath(_assetReference);
_assetGuid = AssetDatabase.AssetPathToGUID(assetPath);
var bundleName = AssetImporter.GetAtPath(assetPath).assetBundleName;
BundleName = bundleName;
AssetName = Path.GetFileNameWithoutExtension(assetPath);
} else {
AssetName = null;
BundleName = null;
}
}
private bool CheckAssetReference() {
return _assetReference == null;
}
#endif
[HideIf("CheckAssetReference")]
[ReadOnly]
public string BundleName;
[HideIf("CheckAssetReference")]
[ReadOnly]
public string AssetName;
[HideIf("CheckAssetReference")]
[SerializeField, ReadOnly]
private string _assetGuid;
public Task<T> LoadAssetFromBundle() {
#if UNITY_EDITOR
if (Application.isPlaying) return BundlesManager.Instance.LoadAsset<T>(BundleName, AssetName);
var task = Task<T>.Factory.StartNew(() => AssetReference);
return task;
#else
return BundlesManager.Instance.LoadAsset<T>(BundleName, AssetName);
#endif
}
}
// Unity does not serialise generics, the trick is to create specific classes for each type of asset you want to serialise
[Serializable]
public class SpriteBundleReference : AssetBundleObjectReference<Sprite> {
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment