Screen Capturing Character for Save/Load Icon
✍ Last Updated : September 6, 2022
🚪 Prequisite Knowledge (Optional)
UploadDescribe InInitial ProgressKnowledge that reader need to know before reading this article
❓ Key Question / Problem / Issue
How to screenshot character to be used as save/load icon
✅ Expected Output/Definition of Done
User can see the saved character in the save/load icon
🎁 Resulting Solution
To capture the character image to be used as save/load icon, we need to use a second camera with render texture set as it’s target texture. The render texture size should be the same as the icon to be used to avoid image stretching.
The icon image need to have transparent background, so the background objects need to be excluded from camera’s culling layer.
Also, set the camera’s clear flag to Solid Color with alpha set to 0
Capturing the image needs to be done at the end of frame, to make sure that the camera has finished rendering, so the Capture process needs to be a coroutine and waiting until the end of frame before start capturing.
public void Capture(int id)
{
gameObject.SetActive(true);
StartCoroutine(Capturing(id));
}
IEnumerator Capturing(int id)
{
yield return new WaitForEndOfFrame();
RenderTexture prevTarget = RenderTexture.active;
RenderTexture.active = GetComponent<Camera>().targetTexture;
texture2D.ReadPixels(rect, 0, 0);
texture2D.Apply();
byte[] bytes = texture2D.EncodeToPNG();
File.WriteAllBytes($"{imagePath}/slot{id}.png", bytes);
onCapture?.Invoke(id, texture2D);
gameObject.SetActive(false);
RenderTexture.active = prevTarget;
}
The capturing start by switching the active render texture to the second camera’s render texture, then reading copying the active render texture’s pixels using ReadPixels. Then encoding the texture2D into PNG format and saving all the bytes into a file using File.WriteAllBytes.
And do not forget to restore the RenderTexture active texture into the previous render texture.