Additional Utilities
Utilities Class
Utilities ClassOverview
Class Definition
using UnityEngine;
namespace SkillfulAI.API
{
public static class Utilities
{
/// <summary>
/// Converts a Texture2D to a Sprite.
/// </summary>
/// <param name="texture">The Texture2D to convert.</param>
/// <returns>A Sprite created from the Texture2D.</returns>
public static Sprite Texture2DToSprite(Texture2D texture)
{
return Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
}
/// <summary>
/// Converts a Texture2D to a RenderTexture.
/// </summary>
/// <param name="texture">The Texture2D to convert.</param>
/// <returns>A RenderTexture created from the Texture2D.</returns>
public static RenderTexture Texture2DToRenderTexture(Texture2D texture)
{
RenderTexture renderTexture = new RenderTexture(texture.width, texture.height, 0);
Graphics.Blit(texture, renderTexture);
return renderTexture;
}
/// <summary>
/// Converts a Texture2D to a Cubemap.
/// Note: This is a basic conversion and assumes the texture is a cross layout of the cubemap faces.
/// </summary>
/// <param name="texture">The Texture2D to convert.</param>
/// <param name="cubemapSize">The size of the cubemap faces.</param>
/// <returns>A Cubemap created from the Texture2D.</returns>
public static Cubemap Texture2DToCubemap(Texture2D texture, int cubemapSize)
{
Cubemap cubemap = new Cubemap(cubemapSize, texture.format, false);
Color[] colors = texture.GetPixels();
int faceWidth = texture.width / 4;
int faceHeight = texture.height / 3;
// Define the face coordinates (in a cross layout)
Rect[] faceRects = {
new Rect(faceWidth * 2, faceHeight * 1, faceWidth, faceHeight), // Positive X
new Rect(faceWidth * 0, faceHeight * 1, faceWidth, faceHeight), // Negative X
new Rect(faceWidth * 1, faceHeight * 2, faceWidth, faceHeight), // Positive Y
new Rect(faceWidth * 1, faceHeight * 0, faceWidth, faceHeight), // Negative Y
new Rect(faceWidth * 1, faceHeight * 1, faceWidth, faceHeight), // Positive Z
new Rect(faceWidth * 3, faceHeight * 1, faceWidth, faceHeight) // Negative Z
};
// Assign pixels to cubemap faces
for (int i = 0; i < 6; i++)
{
Rect faceRect = faceRects[i];
Color[] faceColors = new Color[cubemapSize * cubemapSize];
for (int y = 0; y < cubemapSize; y++)
{
for (int x = 0; x < cubemapSize; x++)
{
faceColors[y * cubemapSize + x] = texture.GetPixel(
(int)(faceRect.x + (x * faceRect.width / cubemapSize)),
(int)(faceRect.y + (y * faceRect.height / cubemapSize))
);
}
}
cubemap.SetPixels(faceColors, (CubemapFace)i);
}
cubemap.Apply();
return cubemap;
}
}
}Detailed Explanation
Usage Example
Conclusion
Last updated