使用Texture2D创建Cubemap

时间:2023-02-08 11:09:20

网上有很多,但大多使用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[0];
    var p_y = texs[1];
    var p_z = texs[2];
    var n_x = texs[3];
    var n_y = texs[4];
    var n_z = texs[5];

    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 = 0; 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[0].GetPixels().Reverse().ToArray(), CubemapFace.PositiveX);
    cubemap.SetPixels(textureArr[1].GetPixels().Reverse().ToArray(), CubemapFace.PositiveY);
    cubemap.SetPixels(textureArr[2].GetPixels().Reverse().ToArray(), CubemapFace.PositiveZ);
    cubemap.SetPixels(textureArr[3].GetPixels().Reverse().ToArray(), CubemapFace.NegativeX);
    cubemap.SetPixels(textureArr[4].GetPixels().Reverse().ToArray(), CubemapFace.NegativeY);
    cubemap.SetPixels(textureArr[5].GetPixels().Reverse().ToArray(), CubemapFace.NegativeZ);

    cubemap.Apply();

    return cubemap;
}

 

 

生成结果:

使用Texture2D创建Cubemap