2
\$\begingroup\$

I'm coming from HTML5 and I'm used to having the 2D Canvas API I can use to generate textures. Is there anything similar in Unity3D?

For example, let's say at runtime I want to render a circle, put 3 initials in the middle and then take the result and put that in a texture. In HTML5 I'd do this

var initials = "GAT";
var textureWidth = 256;
var textureHeight = 256;

// create a canvas
var c = document.createElement("canvas");
c.width = textureWidth;
c.height = textureHeight;
var ctx = c.getContext("2d");

// Set the origin to the center of the canvas
ctx.translate(textureWidth / 2, textureHeight / 2);

// Draw a yellow circle
ctx.fillStyle = "rgb(255,255,0)"; // yellow
ctx.beginPath();
var radius = (Math.min(textureWidth, textureHeight) - 2) / 2;
ctx.arc(0, 0, radius, 0, Math.PI * 2, true);
ctx.fill();

// Draw some black initials in the middle.
ctx.fillStyle = "rgb(0,0,0)";
ctx.font = "60pt Arial";
ctx.textAlign = "center";
ctx.fillText(initials, 0, 30);

// now I can make a texture from that
var tex = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, tex);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, c);
gl.generateMipmap(gl.TEXTURE_2D);

I know I can edit individual pixels in a Unity texture but is there any higher level API for drawing to texture in unity?

\$\endgroup\$
0
2
\$\begingroup\$

Theoretically you could do what you are asking for, however it may run differently and give you different results on different devices.

The Unity way of doing things would be to create a prefab game object that has a circle graphic and a text object attached to it and when you instantiate it you can change the size & color of the circle (even stretch it to an oval if you want) and change the size, text & color of the text object.

If you want to go down that path and need more details let me know what you need more details on.

If you have your heart set on drawing your own texture you will basically need to create an empty texture and then set the color of each pixel via code.

var texture = new Texture2D(2, 2, TextureFormat.ARGB32, false);

texture.SetPixel(0, 0, Color(1.0, 1.0, 1.0, 0.5));
texture.SetPixel(1, 0, Color.red);
texture.SetPixel(0, 1, Color.green);
texture.SetPixel(1, 1, Color.blue);

texture.Apply();

You would of course want to create an entire class to create texture object so you didn't have to do it by hand and there is probably something on the asset store that already does all that, so maybe start there.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.