UnityEditorunity

Unity3D 在Inspector中预览场景

2019-08-13  本文已影响0人  UnityAsk

在Project窗口中点击模型,可以在Preview窗口中进行预览(见下图),但是场景却不能预览。当项目中有比较多的场景,而场景中内容多的时候,我们需要双击每一个打开它才能查看内容,比较耗时。

今天我们来实现一下类似3D物体预览的 场景预览。
当单击场景的时候,可以直接快速的在Inspector中显示他们的内容。
效果如下:


创建一个ScenePreview.cs文件,将下面代码复制进去。完整代码如下:

using System.IO;
using UnityEngine;
using UnityEditor;
using UnityEngine.SceneManagement;
using System.Linq;

[CustomEditor(typeof(SceneAsset))]
[CanEditMultipleObjects]
public class ScenePreview : Editor
{
    const string PreviewFolders = "_scenes"; //你可以修改为你自己的路径,用来存放场景缩略图
    static bool _shouldRefreshDatabase;

    [RuntimeInitializeOnLoadMethod]
    public static void CaptureScreenshot()
    {
        var previewPath = GetPreviewPath(SceneManager.GetActiveScene().name);
        var dir = Path.GetDirectoryName(previewPath);
        if (!Directory.Exists(dir))
        {
            Directory.CreateDirectory(dir);
        }

        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 previewWidth = 200;
        var previewHeight = 200;

        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(
                "还没有场景{0}的预览图{1}. 请切换到这个场景然后点击播放,会自动生成该场景的缩略图",
                sceneName,
                previewPath),
                MessageType.Info);
        }
        else
        {
            GUILayout.Button(preview,GUILayout.Width(width),GUILayout.Height(height));
        }
    }

    static string GetPreviewPath(string sceneName)
    {
        return string.Format("{0}/{1}/Resources/{2}.png", Application.dataPath, PreviewFolders, sceneName);
    }
}

基本原理就是当运行一个场景的时候,给这个场景截一张图,然后当选中时在Inspector中显示截图。

上一篇下一篇

猜你喜欢

热点阅读