最近做的一个2D小游戏,游戏的关卡选择界面,需要将关卡内容做成缩略图显示在关卡选择图标上面。
随便百度的一个关卡选择界面,图一,游戏界面,图二,现需将游戏界面的内容,以缩略图的形式显示在关卡选择界面对应的图标
动态生成关卡预览缩略图动态生成关卡预览缩略图
- 记录需要预览的关卡
- 利用协程 依次生成预览场景,避免在某一帧做大量计算
- 相机获取预览场景缩略图
- 关卡图标赋值,显示缩略图
- 显示下一个关卡图标
主要代码如下,附注释,其余代码可以及场景设置,可以下载项目查看:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PreviewManager : MonoBehaviour
{
public static PreviewManager Instance;
// 预览场景,并不是Scene,这里指Scene里,所有需要在缩略图中预览的GameObject
//保存待生成预览图的信息队列
Dictionary<int, RawImage> toShowDic = new Dictionary<int, RawImage>();
//保存已生成的预览图,第二次直接获取,不再生成
Dictionary<int, Texture2D> textureDic = new Dictionary<int, Texture2D>();
//预览场景相机
Camera previewCamera;
//生成预览场景的方法,可由外界传入
System.Action<int> showPreviewMapFunc;
//默认图
Texture2D defaultTexture;
void Awake()
{
Instance = this;
}
public void Init(Camera previewUseCamera, Texture2D defaultTexture2D, System.Action<int> action)
{
previewCamera = previewUseCamera;
defaultTexture = defaultTexture2D;
showPreviewMapFunc = action;
}
/// <summary>
/// Sets the texture by level.
/// </summary>
/// <param name="level">Stage level.</param>
/// <param name="iconImage">Icon image.</param>
public void SetTextureByLevel(int level, RawImage iconImage)
{
if (textureDic.ContainsKey(level))
{
//若预览图已经生成,直接赋值
iconImage.texture = textureDic[level];
}
else
{
//先显示默认图
iconImage.texture = defaultTexture;
//若预览图没有生成,生成并赋值
StopAllCoroutines();
toShowDic.Add(level, iconImage);
StartCoroutine(ShowAllMap());
}
}
//生成所有预览图
IEnumerator ShowAllMap()
{
while (toShowDic.Count > 0)
{
yield return StartCoroutine(ShowOneMap());
//可在此设置间隔时间,增加下个预览图出现的时间,调节整体效果
//yield return new WaitForSeconds(0.5f);
}
}
//生成一个预览图
IEnumerator ShowOneMap()
{
//获取待生成队列字典中第一组数据
int stageLevel = 0;
RawImage rawImage = null;
foreach (var item in toShowDic)
{
stageLevel = item.Key;
rawImage = item.Value;
break;
}
if (rawImage == null)
yield break;
//动态生成预览场景
if (showPreviewMapFunc != null)
showPreviewMapFunc(stageLevel);
else
{
rawImage.texture = defaultTexture;
yield break;
}
//等待一帧
yield return new WaitForEndOfFrame();
//RenderTexture接收渲染相机结果
RenderTexture renderTexture = new RenderTexture(200, 200, 16);
previewCamera.targetTexture = renderTexture;
previewCamera.Render();
//从RenderTexture获取Texture2D,将RenderTexture从GPU拷贝到CPU
RenderTexture.active = renderTexture;
Texture2D texture2D = new Texture2D(200, 200);
texture2D.ReadPixels(new Rect(0, 0, texture2D.width, texture2D.height), 0, 0);
texture2D.Apply();
//对目标图片赋值
rawImage.texture = texture2D;
//添加到字典,下次需要获取texture2D时,可直接通过字典获取,只会生成一次
textureDic.Add(stageLevel, texture2D);
//移出待生成队列字典
toShowDic.Remove(stageLevel);
//等待一帧
yield return new WaitForEndOfFrame();
}
}