使用Texture2D创建Cubemap

时间:2022-06-21 17:50:50

网上有很多,但大多使用Camera.RenderToCubemap接口,不能满足需求。

写了段代码可以载入Texture2D生成Cubemap(在Editor下运行):

/// <summary>
/// Array order [Px, Py, Pz, Nx, Ny, Nz](Execute in editor)
/// </summary>
public static Cubemap BuildCubemap(Texture2D[] texs)
{
var p_x = texs[];
var p_y = texs[];
var p_z = texs[];
var n_x = texs[];
var n_y = texs[];
var n_z = texs[]; if (p_x.width != p_x.height) throw new System.Exception("Create Error! width != height"); var textureArr = new Texture2D[] { p_x, p_y, p_z, n_x, n_y, n_z };
for (int i = ; i < textureArr.Length; i++)
{
var item = textureArr[i]; var path = AssetDatabase.GetAssetPath(item);
var textureImporter = AssetImporter.GetAtPath(path) as TextureImporter;
textureImporter.textureFormat = TextureImporterFormat.RGB24;
textureImporter.isReadable = true;
textureImporter.SaveAndReimport(); textureArr[i] = AssetDatabase.LoadAssetAtPath<Texture2D>(path);
} var cubemap = new Cubemap(p_x.width, TextureFormat.RGB24, false); //Set CubemapFace.(force fix texture format question).
cubemap.SetPixels(textureArr[].GetPixels().Reverse().ToArray(), CubemapFace.PositiveX);
cubemap.SetPixels(textureArr[].GetPixels().Reverse().ToArray(), CubemapFace.PositiveY);
cubemap.SetPixels(textureArr[].GetPixels().Reverse().ToArray(), CubemapFace.PositiveZ);
cubemap.SetPixels(textureArr[].GetPixels().Reverse().ToArray(), CubemapFace.NegativeX);
cubemap.SetPixels(textureArr[].GetPixels().Reverse().ToArray(), CubemapFace.NegativeY);
cubemap.SetPixels(textureArr[].GetPixels().Reverse().ToArray(), CubemapFace.NegativeZ); cubemap.Apply(); return cubemap;
}

生成结果:

使用Texture2D创建Cubemap