- Home /
Serialize texture modified by Graphics Library
I'm trying to export a texture that is modified using the Graphics Library during runtime.
private IEnumerator buildPreview(PaintBucket pb){previewTile.SetActive(true); previewCam.gameObject.SetActive(true);
Vector3 sixths = new Vector3(0,60,0);
previewTile.GetComponent<Renderer>().material = palette[pb.index].mat;
pb.preview = new Texture2D(120,72);
//Size is 327 bytes
pb.preview.filterMode = FilterMode.Point;
for(int j = 0; j < 2; j++){
for(int k = 0; k < 3; k++){
previewCam.Render();
Graphics.CopyTexture(preview,0,0,0,0,40,36,pb.preview,0,0,(40*k),(36*j));
pb.preview.IncrementUpdateCount();
previewTile.GetComponent<Transform>().Rotate(sixths, Space.World);}}
//Size somehow remains 327 bytes
previewTile.SetActive(false); previewCam.gameObject.SetActive(false);
StartCoroutine(saveImage(control.dc.direc + previews + palette[pb.index].name + ".png",pb.preview));
pb.copy = new Texture2D(40,36);
pb.copy.filterMode = 0;
pb.setFrame(0);
pb.image.texture = pb.copy;
yield break;
}
public IEnumerator saveImage(string path, Texture2D t){FileStream file = new FileStream(path,FileMode.OpenOrCreate, FileAccess.Write, FileShare.Write);
byte[] bits = t.EncodeToPNG();
print(bits.Length);
Task j = file.WriteAsync(bits,0,bits.Length);
yield return new WaitUntil(() => j.IsCompleted);
yield break;}
I've tried copying the data to an additional texture2D object using the graphics library, using Setpixels / GetPixels, using GetRawTextureData, using raw assignment, storing to a RawImage object, and calling Apply().
So far as I can tell, the data doesn't update CPU-side, and so the texture object (when referenced by the script) doesn't conform to the changes made by the Graphics Library.
Help?
Answer by Cactus_Fantastico · May 19, 2021 at 09:39 PM
Got it.
private IEnumerator buildPreview(PaintBucket pb){previewTile.SetActive(true); previewCam.gameObject.SetActive(true); Vector3 sixths = new Vector3(0,60,0); previewTile.GetComponent<Renderer>().material = palette[pb.index].mat; pb.preview = new Texture2D(120,72); pb.preview.filterMode = FilterMode.Point; for(int j = 0; j < 2; j++){ for(int k = 0; k < 3; k++){ previewCam.Render(); Graphics.CopyTexture(preview,0,0,0,0,40,36,paintpre,0,0,(40*k),(36*j)); previewTile.GetComponent<Transform>().Rotate(sixths, Space.World);}} previewTile.SetActive(false); previewCam.gameObject.SetActive(false); Graphics.SetRenderTarget(paintpre); pb.preview.ReadPixels(new Rect(0,0,120,72),0,0,true); pb.preview.Apply(); StartCoroutine(saveImage(control.dc.direc + previews + palette[pb.index].name + ".png",pb.preview)); pb.copy = new Texture2D(40,36); pb.copy.filterMode = 0; pb.setFrame(0); pb.image.texture = pb.copy; yield break; }
To anyone attempting to do this in the future, copy renders to a RenderTexture, ReadPixels from that RenderTexture into a Texture2D, and then apply.