Skip to content

Instantly share code, notes, and snippets.

@giacomelli
Last active November 30, 2020 15:11
Show Gist options
  • Save giacomelli/f74a23107fe862ae7501002ac856f932 to your computer and use it in GitHub Desktop.
Save giacomelli/f74a23107fe862ae7501002ac856f932 to your computer and use it in GitHub Desktop.
using UnityEngine;
using UnityEditor;
using UnityEngine.SceneManagement;
using System.Linq;
/// <summary>
/// Scene preview.
/// https://diegogiacomelli.com.br/unity3d-scenepreview-inspector/
/// </summary>
[CustomEditor(typeof(SceneAsset))]
[CanEditMultipleObjects]
public class ScenePreview : Editor
{
// Change this to a folder in your project.
// Maybe the folder where your scenes are located. Remember to create a subfolder called "Resources" inside of it.
const string PreviewFolders = "_scenes";
const float EditorMargin = 50;
const float PreviewMargin = 5;
static bool _shouldRefreshDatabase;
[RuntimeInitializeOnLoadMethod]
public static void CaptureScreenshot()
{
var previewPath = GetPreviewPath(SceneManager.GetActiveScene().name);
Debug.LogFormat("Saving scene preview at {0}", previewPath);
ScreenCapture.CaptureScreenshot(previewPath);
Debug.LogFormat("Scene preview saved at {0}", previewPath);
_shouldRefreshDatabase = true;
}
public override void OnInspectorGUI()
{
if (_shouldRefreshDatabase)
{
AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate);
_shouldRefreshDatabase = false;
}
var sceneNames = targets.Select(t => ((SceneAsset)t).name).OrderBy(n => n).ToArray();
var previewsCount = sceneNames.Length;
var previewWidth = Screen.width;
var previewHeight = (Screen.height - EditorMargin * 2 - (PreviewMargin * previewsCount)) / previewsCount;
for (int i = 0; i < sceneNames.Length; i++)
{
DrawPreview(i, sceneNames[i], previewWidth, previewHeight);
}
}
void DrawPreview(int index, string sceneName, float width, float height)
{
var previewPath = GetPreviewPath(sceneName);
var preview = Resources.Load(sceneName) as Texture;
if (preview == null)
{
EditorGUILayout.HelpBox(string.Format(
"There is no image preview for scene {0} at {1}. Please play the scene on editor and image preview will be captured automatically.",
sceneName,
previewPath),
MessageType.Info);
}
else
{
GUI.DrawTexture(new Rect(index, EditorMargin + index * (height + PreviewMargin), width, height), preview, ScaleMode.ScaleToFit);
}
}
static string GetPreviewPath(string sceneName)
{
return string.Format("{0}/{1}/Resources/{2}.png", Application.dataPath, PreviewFolders, sceneName);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment