texCoords rect for GUI.DrawTextureWithTexCoords

Hi,

I’m trying to write a simple sprite animation system for 2D on the GUI layer and am running into problems with GUI.DrawTextureWithTexCoords. I have a sprite sheet that’s 32x256px at 32x32 per sprite (ie. 1x8 sprites), but no matter what I set the texCoords Rect to I can’t seem to get any of them to display.

Rects I’ve tried for texCoord:

  • (0, 0, 32, 32)
  • (0, 32, 32 ,32)
  • (0, -32, 32, 32)
  • (0, 0, 256, 32)

All of these give me the same result - if alphaBlend is true, I will always get a white square at near-full transparency, if alphaBlend is false, I will just get a white square.

Replacing DrawTextureWithTexCoords with DrawTexture gives me the full spritesheet squashed down to 32x32, but works fine otherwise.

Has someone successfully used GUI.DrawTextureWithTexCoords and can explain how the texCoords Rect works?

Thanks a lot :slight_smile:

I had the same problem, turns out the texture coordinates are normalized. So in your case you would have 1/8, 2/8, 3/8… positions. i.e a percentage.

GUI.DrawTextureWithTexCoords(new Rect(0,0,32,32), theTexture, new Rect(0f,0f,0.125f,1f),true);

It’s also worth noting that the texCoord Y-axis is opposite to the destination.

In other words to draw the bottom-left corner, you must use

GUI.DrawTextureWithTexCoords(
    new Rect(pos.left, pos.top, dstWidth, dstHeight),
    texture
    new Rect(0f, 0f, srcWidth, srcHeight));

Maybe someone still needs this:

Rect texCoord(x, y, timesx, timesy)

Here:
(x, y) is a position to START drawing texture FROM. Texture is drawn left-to-right and up-to-down.

(timesx, timesy) is a thing that says how many times Unity must draw the texture.
In the example below (tx, ty) = (2.5, 1.5) (and (x, y), obviously = (0,0))
[87876-q31hcdkuiwa-копия.jpg|87876]

And here is an example that uses both pairs of parameters:

UP: in the comments

PS Sorry for images, I’m not a good artist actually