Skip to content

Instantly share code, notes, and snippets.

@shadowmint
Created March 17, 2021 13:48
Show Gist options
  • Save shadowmint/5417cdf37dc947e8ae862d54527127a4 to your computer and use it in GitHub Desktop.
Save shadowmint/5417cdf37dc947e8ae862d54527127a4 to your computer and use it in GitHub Desktop.
using System;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEngine;
[System.Serializable]
public struct NPrefabRef<T> : IDisposable
{
public GameObject root;
public T data;
public string assetPath;
public bool isNew;
public void Dispose()
{
#if UNITY_EDITOR
if (root == null) return;
if (isNew)
{
UnityEngine.Object.DestroyImmediate(root);
}
else
{
PrefabUtility.UnloadPrefabContents(root);
}
#endif
}
}
public class NPrefabService
{
private static string NormalizePath(string path)
{
var pathComponents = path.Split('/').Where(i => !string.IsNullOrEmpty(i)).ToList();
var partial = pathComponents.Count == 0 ? "" : pathComponents[0];
for (var i = 1; i < pathComponents.Count; i++)
{
partial = Path.Combine(partial, pathComponents[i]);
}
return partial;
}
/// <summary>
/// Return the full physical system path for the given asset path.
/// </summary>
public string PhysicalPath(string path)
{
var assetPath = NormalizePath(path);
return Path.Combine(UnityEngine.Application.dataPath, assetPath);
}
public NPrefabRef<T> LoadPrefab<T>(string assetPath)
{
var physicalPath = PhysicalPath(assetPath) + ".prefab";
Debug.Log(physicalPath);
Debug.Log(File.Exists(physicalPath));
GameObject instance = null;
instance = PrefabUtility.LoadPrefabContents(physicalPath);
Debug.Log($"Loaded: {instance}");
var rtn = new NPrefabRef<T>()
{
root = instance,
data = instance.GetComponent<T>(),
assetPath = assetPath,
isNew = false
};
if (rtn.data == null)
{
rtn.Dispose();
throw new Exception($"No element of type {nameof(T)} on prefab at: {physicalPath}");
}
return rtn;
}
public void SavePrefab<T>(NPrefabRef<T> prefabRef)
{
var assetPath = PhysicalPath(prefabRef.assetPath) + ".prefab";
PrefabUtility.SaveAsPrefabAssetAndConnect(prefabRef.root, assetPath, InteractionMode.AutomatedAction);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment