Created
January 7, 2022 11:11
-
-
Save usbharu/fdc3e2c29d9c2fb8acea32509fbe9ee3 to your computer and use it in GitHub Desktop.
PreviewRenderUtilityExample
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEditor; | |
using UnityEngine; | |
using UnityLogging; | |
public class PreviewRenderUtilityExample : EditorWindow | |
{ | |
private GameObject _gameObject; | |
private GameObject previewObject; | |
[MenuItem("Window/PreviewRenderUtilityExample")] | |
private static void CreateWindow() | |
{ | |
var win = GetWindow<PreviewRenderUtilityExample>(); | |
win.Show(); | |
} | |
private PreviewRenderUtility _previewRenderUtility; | |
private Texture _outputTexture; | |
private void OnEnable() | |
{ | |
if (_previewRenderUtility != null) | |
_previewRenderUtility.Cleanup(); | |
_previewRenderUtility = new PreviewRenderUtility(true); | |
System.GC.SuppressFinalize(_previewRenderUtility); | |
var camera = _previewRenderUtility.camera; | |
camera.fieldOfView = 30f; | |
camera.nearClipPlane = 0.3f; | |
camera.farClipPlane = 1000; | |
camera.transform.position = new Vector3(2.5f, 1f, -2.5f); | |
camera.transform.LookAt(Vector3.zero); | |
// var obj = GameObject.CreatePrimitive(PrimitiveType.Cube); | |
// DestroyImmediate(obj); | |
} | |
private RenderTexture CreatePreviewTexture(GameObject obj) | |
{ | |
if (obj == null) | |
{ | |
return null; | |
} | |
_previewRenderUtility.BeginPreview(new Rect(0, 0, 128, 128), GUIStyle.none); | |
_previewRenderUtility.lights[0].transform.localEulerAngles = new Vector3(30, 30, 0); | |
_previewRenderUtility.lights[0].intensity = 2; | |
_previewRenderUtility.AddSingleGO(obj); | |
_previewRenderUtility.camera.Render(); | |
return (RenderTexture) _previewRenderUtility.EndPreview(); | |
} | |
private void OnGUI() | |
{ | |
GameObject oldGameObject = _gameObject; | |
_gameObject = EditorGUILayout.ObjectField("Object", _gameObject, typeof(GameObject), true) as GameObject; | |
if (oldGameObject != null && _gameObject != null && !_gameObject.Equals(oldGameObject)) | |
{ | |
oldGameObject = _gameObject; | |
Logging.Log("Instantiate", "Preview"); | |
DestroyImmediate(previewObject); | |
previewObject = Instantiate(oldGameObject); | |
} | |
if (_previewRenderUtility != null || _outputTexture != null) | |
{ | |
// if (_gameObject!=null) | |
{ | |
Logging.Log("start preview", "Preview"); | |
_outputTexture = CreatePreviewTexture(previewObject); | |
// GUI.DrawTexture(new Rect(0,0, 300, 300), _outputTexture); | |
GUILayout.Box(_outputTexture); | |
} | |
} | |
} | |
private void OnDisable() | |
{ | |
_previewRenderUtility.Cleanup(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment