- Home /
Any idea how to use PreviewRenderUtility ?
I was coding and I typed "preview.." and saw PreviewRenderUtility. A public class with function that seem to allows up to now quickly draw our own preview windows in the unity Editor .... But it has not been documented yet so attempts to make it work are hit and miss.
Anyone used this before and got it working ? Could you how me how it is used ?
If I am correct it should allows us to finally do things like this easily .
Answer by chingwa · Jul 11, 2017 at 09:46 PM
@DMDev I noticed code for this after viewing this Unite talk here: https://www.youtube.com/watch?v=sd9KotQ2PhA
You can see them talk about asset previews around the 8:00 minute mark. This is the code they use:
PreviewRenderUtility renderUtility = new PreviewRenderUtility();
void OnGUI(){ Rect rect = new Rect(40,200,200,200); renderUtility.BeginPreview(rect, ""); renderUtility.DrawMesh(previewModel.mesh, Vector3.one, Quaternion.identity, previewModel.material,0); renderUtility.EndAndDrawPreview(rect); }
Answer by EJSainz · Jul 22, 2019 at 02:38 PM
Just in case somebody stomps here looking for some info on PreviewRenderUtility, I just gathered the following code from here and there to draw a prefab using it:
void BeginDraw(Rect r)
{
if (prevRenderer == null)
prevRenderer = new PreviewRenderUtility();
prevRenderer.camera.transform.position = camPosition;
prevRenderer.camera.transform.LookAt(Vector3.zero, Vector3.up);
prevRenderer.camera.farClipPlane = 30;
prevRenderer.lights[0].intensity = 0.5f;
prevRenderer.lights[0].transform.rotation = Quaternion.Euler(30f, 30f, 0f);
prevRenderer.lights[1].intensity = 0.5f;
prefabTransform.SetTRS(prefabTranslation, Quaternion.Euler(prefabRotation), prefabScale);
prevRenderer.BeginPreview(r, GUIStyle.none);
}
void EndDraw(Rect r)
{
bool fog = RenderSettings.fog;
Unsupported.SetRenderSettingsUseFogNoDirty(false);
prevRenderer.camera.Render();
Unsupported.SetRenderSettingsUseFogNoDirty(fog);
Texture texture = prevRenderer.EndPreview();
GUI.DrawTexture(r, texture);
}
public void DrawRenderPreview()
{
if (prefab != null)
{
MeshFilter[] meshFilters = prefab.GetComponentsInChildren<MeshFilter>();
for (int i = 0; i < meshFilters.Length; i++)
{
if (meshFilters[i].sharedMesh)
{
MeshRenderer meshRenderer = meshFilters[i].gameObject.GetComponent<MeshRenderer>();
for (int j = 0; j < meshFilters[i].sharedMesh.subMeshCount; j++)
if (meshRenderer != null)
{
prevRenderer.DrawMesh(
meshFilters[i].sharedMesh,
prefabTransform * meshRenderer.transform.localToWorldMatrix,
meshRenderer.sharedMaterials[j],
j);
}
}
}
}
}
private void OnGUI()
{
Rect r = new Rect(0.0f, 0.0f, position.width, position.height);
BeginDraw(r);
DrawRenderPreview();
EndDraw(r);
}
This code will draw a GameObject referenced in the prefab variable, and it's part of an EditorWindow. I'm sorry I have not enough time to prepare the full working class, but the code is pretty self explanatory, and you can have it working in no time.