Rendering a portion of a texture using GUI.Box()?


I have a texture that is 256x64. I need to render from 0,0 to 63,63 in this texture (A 64x64 sub-rect). How can I do this using GUI.Box()?

I've tried specifying a GUIStyle that sets contentOffset to (0,0) and fixedWidth/fixedHeight to 64,64 but this didn't work.


I think you can use GUI.DrawTexture, e.g. (C#):

// Edited - Sorry for the mistake.  Here's an example of updating the pixels as described elsewhere:
//  GUI.DrawTexture( myRect, myTexture, ScaleMode.ScaleAndCrop );

Color[] colors = textureToCrop.GetPixels( (int)cropRect.x, (int)cropRect.y, (int)cropRect.width, (int)cropRect.height );
croppedTexture = new Texture2D( (int)cropRect.width, (int)cropRect.height );
croppedTexture.SetPixels( colors );
croppedTexture.Apply( false );

Take a look at Graphics.DrawTexture.

You can specify a material and, with so, UV coordinates. This way you can draw only a portion of your texture inside OnGUI calls. You must end up with something like it:

if (Event.current.type == EventType.Repaint) 
   Graphics.DrawTexture(screenRect, texture, new Rect(u, v, uWidth, vHeight), leftBorder, rightBorder, topBorder, bottomBorder, material);


new Rect(u, v, uWidth, vHeight)

is your sourceRect (texture portion that you want to draw).

There are several ways, copy only that part of the texture to a new texture using GetPixels (or something like that I dont remember pretty well now).

another one is render to texture from another camera only that part of the texture (which I think is kinda hacky)

I would use the 1rst one I suggested you.

Naruse was correct, although I will flesh out his answer a bit:

Use Texture2D.GetPixels to get the area of pixels you want. Then, create a new Texture2D object, and call Texture2D.SetPixels to write the extracted section of pixels to the new texture object. Then, call `GUI.Box()` or `GUI.Texture()` or whatever else you want to use, but using the new Texture2D object you created instead of the old one.

My question would be. Do I gain something from having all my textures in a single, let’s say, png file then do this to create subtextures to apply? Or it is better if the textures are split by the artist?