官方论坛上面老外讨论的解答
生成CubeMap使用的是Camera内置的接口 Camera.RenderToCubemap
docs
using UnityEditor;
using UnityEngine;
public class CubeMapMaker : ScriptableWizard
{
public Transform renderFromPosition=null;
public Cubemap cubemap=null;
void OnWizardUpdate()
{
//选择一个gameObject用于确定渲染起始位置,同时选择一个cubemap用于渲染
helpString = "Select transform to render from and cubemap to render into";
bool isValid = (renderFromPosition != null) && (cubemap != null);
}
void OnWizardCreate()
{
//创建用于渲染的临时相机
GameObject gameObject = new GameObject("CubemapCamera");
gameObject.AddComponent<Camera>();
//将临时相机绑到目标物体上
gameObject.transform.position = renderFromPosition.position;
gameObject.transform.rotation = Quaternion.identity;
//渲染为cubemap
gameObject.GetComponent<Camera>().RenderToCubemap(cubemap);
//删除临时相机
DestroyImmediate(gameObject);
}
[MenuItem("GameObject/Render2Cubemap")]
static void Render2Cubemap()
{
ScriptableWizard.DisplayWizard<CubeMapMaker>(
"Render Cubemap", "Render"
);
}
}
导出Cuebmap是通过读取CubemapFace然后用Texture2D的功能导出为图片,但是由于一些问题,导出图片之前要先将Texture2D垂直和水平翻转
using UnityEngine;
using UnityEditor;
using System.Linq;
using System.IO;
public class SaveCubeMap2Png : ScriptableWizard
{
public Cubemap cubemap = null;
[MenuItem("GameObject/SaveCubeMap2Png")]
private static void MenuEntryCall()
{
ScriptableWizard.DisplayWizard<SaveCubeMap2Png>("SaveCubeMap2Png", "Save");
}
public static void FlipPixels(Texture2D texture, bool flipX, bool flipY)
{
Color32[] originalPixels = texture.GetPixels32();
var flippedPixels = Enumerable.Range(0, texture.width * texture.height).Select(index =>
{
int x = index % texture.width;
int y = index / texture.width;
if (flipX)
x = texture.width - 1 - x;
if (flipY)
y = texture.height - 1 - y;
return originalPixels[y * texture.width + x];
}
);
texture.SetPixels32(flippedPixels.ToArray());
texture.Apply();
}
private void OnWizardCreate()
{
int width = cubemap.width;
int height = cubemap.height;
Texture2D texture2D = new Texture2D(width, height, TextureFormat.RGB24, false);
for (int i = 0; i < 6; i++)
{
texture2D.SetPixels(cubemap.GetPixels((CubemapFace)i));
//翻转像素,由于某种原因,导出的图片需要进行翻转
FlipPixels(texture2D, true, true);
//此处导出为png
File.WriteAllBytes(Application.dataPath + "/" + cubemap.name + "_" + ((CubemapFace)i).ToString() + ".png", texture2D.EncodeToPNG());
}
DestroyImmediate(texture2D);
}
private void OnWizardUpdate()
{
helpString = "Select cubemap to save to individual .png";
if (Selection.activeObject is Cubemap && cubemap == null)
cubemap = Selection.activeObject as Cubemap;
isValid = (cubemap != null);
}
}