I'm trying to optimize the following code as looping that many times to get every pixel of a texture is extremely time consuming!
I have 3 textures, generated elsewhere that need to be merged and then saved to disk.
I've tried using SetPixels and GetPixels but that isn't particularly useful as using it multiple times just replaces the whole texture rather than only replacing non transparent pixels. The following is my function so far:
public void savePNG()
{
stationWidth = PlayerPrefs.GetInt("Station Width");
stationHeight = PlayerPrefs.GetInt("Station Height");
Debug.Log(stationWidth + ", " + stationHeight);
Texture2D spaceStation = new Texture2D(stationWidth*256, stationHeight*256, TextureFormat.ARGB32, false);
spaceStation = new Texture2D(stationWidth*256, stationHeight*256, TextureFormat.ARGB32, false);
Color Test;
floorTex = new Texture2D(stationWidth*256, stationHeight*256, TextureFormat.ARGB32, false);
wallTex = new Texture2D(stationWidth*256, stationHeight*256, TextureFormat.ARGB32, false);
roomTex = new Texture2D(stationWidth*256, stationHeight*256, TextureFormat.ARGB32, false);
floorTex.LoadImage(File.ReadAllBytes(Application.dataPath + "/../floorTexture.png"), false);
wallTex.LoadImage(File.ReadAllBytes(Application.dataPath + "/../wallTexture.png"), false);
roomTex.LoadImage(File.ReadAllBytes(Application.dataPath + "/../roomTexture.png"), false);
for(int row = 0; row < stationWidth*256; row ++)
{
for(int col = 0; col < stationHeight*256; col ++)
{
Test = floorTex.GetPixel(row,col);
if(Test.a != 0.0f)
{
spaceStation.SetPixel(row, col, floorTex.GetPixel(row,col));
}
else
{
spaceStation.SetPixel(row, col, Color.white);
}
Test = wallTex.GetPixel(row,col);
if(Test.a != 0.0f)
{
spaceStation.SetPixel(row, col, wallTex.GetPixel(row,col));
}
Test = roomTex.GetPixel(row,col);
if(Test.a != 0.0f)
{
spaceStation.SetPixel(row, col, roomTex.GetPixel(row,col));
}
}
}
spaceStation.Apply();
byte[] bytes = spaceStation.EncodeToPNG();
File.WriteAllBytes(Application.dataPath + "/../SpaceStation.png", bytes);
}
I'm not sure where to go from here, any ideas or suggestions would be greatly appreciated!
Additional
The GetPixels and SetPixels code I was trying looked like this:
spaceStation.SetPixels(floorTex.GetPixels(0, 0, stationWidth*256, stationHeight*256));
spaceStation.SetPixels(wallTex.GetPixels(0 ,0, stationWidth*256, stationHeight*256));
spaceStation.SetPixels(roomTex.GetPixels(0, 0, stationWidth*256, stationHeight*256));
Each SetPixels overwrote the previous ones completely where I would want transparent pixels not to overwrite any pixel at all so the details would show through