- Home /
add text to a Texture2D while game is running
My game has a feature where it takes a screenshot (Texture2D) and posts it to social media platforms - all pretty standard. I'd like to add some text to the screenshot (score etc) but I'm stuck. Any tips? Thanks
Answer by BillyMFT · Feb 18, 2015 at 01:28 PM
I ended up doing it with a RenderTexture. Here were the steps I took.
Duplicate the main game camera, call it "ScreenshotCam" and set it to a lower depth (not sure if that was required)
Make a new render texture in the project panel and set it to a decent size
Make the render texture the "target Texture" of the ScreenshotCam
Add some UI text for score and a UI image for the game logo. Put these both on a layer that is only rendered by the ScreenshotCam (ie uncheck the layer in the culling mask dropdown of the main camera)
output the current score to the UI text box as the game is being player
Make the render texture created in step 2 active while taking the screenshot.
Here is the capture function I'm using.
function CaptureScreen() {
yield WaitForEndOfFrame();
var currentRT = RenderTexture.active;
RenderTexture.active = scoreRenderTexture;
var tex = new Texture2D(screenshotScoreCamera.pixelWidth, screenshotScoreCamera.pixelHeight, TextureFormat.RGB24, false);
// Read screen contents into the texture
tex.ReadPixels(screenshotScoreCamera.pixelRect, 0, 0);
tex.Apply();
RenderTexture.active = currentRT;
return tex;
}
Hope others find this useful.
Answer by hexagonius · Feb 17, 2015 at 01:23 PM
This should help you, but in general looking into the Texture2D documentation gives you an idea of how to modify a texture (by GetPixels, SetPixels and Apply):
Adding Text-To-Texture at Runtime in Unity3D Without Using Render Texture
Thanks. I did see that tutorial in my searches but it seemed a bit dated. Unity iOS can RenderTextures now so I thought there would be a simpler solution. Do you know of any tutorials for adding text to a texture using SetPixels? The unity docs just shows how to make patterns and add colours to pixels. I've read some stuff about using a camera to render some gui text but nothing that actually explains how to do it and add it to a Texture2D.
Your answer
Follow this Question
Related Questions
Display Short message on screen each button press 0 Answers
Wrapping dynamic text around an object. 1 Answer
Render a text on the sprite 1 Answer
Save png with text overlay 3 Answers
Texture.Apply() Crashes at Resolutions under 1920x1080 1 Answer