Skip to content

Instantly share code, notes, and snippets.

@kalineh
Created July 13, 2017 18:09
Show Gist options
  • Save kalineh/7922ca0d9a517253316f523ce735b16a to your computer and use it in GitHub Desktop.
Save kalineh/7922ca0d9a517253316f523ce735b16a to your computer and use it in GitHub Desktop.
Simple nested prefab utility with editor preview.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
[CustomEditor(typeof(PrefabNode))]
public class PrefabNodeEditor
: Editor
{
private GameObject previewPrefab;
private GameObject previewObject;
public void OnSceneGUI()
{
if (Application.isPlaying)
return;
var self = target as PrefabNode;
if (self.prefab == null)
{
if (previewObject != null)
{
DestroyImmediate(previewObject);
previewObject = null;
}
return;
}
if (previewPrefab != self.prefab)
{
if (previewObject != null)
{
DestroyImmediate(previewObject);
previewObject = null;
}
}
if (previewObject == null)
{
previewPrefab = self.prefab;
previewObject = GameObject.Instantiate(previewPrefab);
previewObject.transform.SetParent(self.transform, false);
previewObject.transform.localPosition = Vector3.zero;
previewObject.transform.localRotation = Quaternion.identity;
}
}
public void OnDisable()
{
if (previewObject != null)
{
previewObject.name = "dead";
DestroyImmediate(previewObject);
previewObject = null;
}
}
}
#endif
public class PrefabNode
: MonoBehaviour
{
public GameObject prefab;
private GameObject instance;
public void OnEnable()
{
if (prefab == null)
return;
if (instance != null)
return;
instance = GameObject.Instantiate(prefab);
instance.transform.SetParent(transform, false);
instance.transform.localPosition = Vector3.zero;
instance.transform.localRotation = Quaternion.identity;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment