dynamic 2d texture creation in unity from script

Posted by gman on Game Development See other posts from Game Development or by gman
Published on 2013-10-27T18:08:35Z Indexed on 2013/10/27 22:02 UTC
Read the original article Hit count: 291

Filed under:

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?

© Game Development or respective owner

Related posts about unity