Search Unity

Try to Show a sprite in GUI.DrawTexture

Discussion in 'Scripting' started by Potote, Nov 23, 2014.

  1. Potote

    Potote

    Joined:
    Oct 13, 2014
    Posts:
    24
    Hi all

    I have a problem when try to show only one sprite from a template with multiples sprites.

    I have a gameObject with one of this sprites, and store it like sprite renderer, when execute the game, it´s show properly, but when i try to show it in a GUI.drawtexture, show all the sprites instead of the sprite only in the spriterenderer.

    The code is this:

    Code (CSharp):
    1. SpriteRenderer archer_sprite = GetComponent<SpriteRenderer>();
    2.         GUI.DrawTexture(new Rect (25, 25, 75, 75), archer_sprite.sprite.texture);
    Thanks beforehand
     
  2. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    You'd need to use GUI.DrawTextureWithTexCoords, where you use the sprite.rect to draw only part of the texture.

    --Eric
     
  3. imprity

    imprity

    Joined:
    Aug 13, 2019
    Posts:
    1
    Made a function just for that!

    Code (CSharp):
    1. public static void GUIDrawSprite(Rect rect, Sprite sprite){
    2.         Rect spriteRect = sprite.rect;
    3.         Texture2D tex = sprite.texture;
    4.         GUI.DrawTextureWithTexCoords(rect, tex, new Rect(spriteRect.x / tex.width, spriteRect.y / tex.height, spriteRect.width/ tex.width, spriteRect.height / tex.height));
    5.     }
    pretty sure it works

    ps: rect there at argument doesnt really consider sprite aspect ratio so get that with sprite.rect.width and height if you want to match the aspect ratio
     
  4. joan_stark

    joan_stark

    Joined:
    Jul 24, 2018
    Posts:
    43
    Hey, can you explain how would I take into consideration sprite aspect ratio, I don't quite understand what do you mean with taking into account sprite.rect.width. Thanks!