Search Unity

Question regarding GUI Background repeat solution

Discussion in 'Scripting' started by Rukas90, Jun 6, 2019.

  1. Rukas90

    Rukas90

    Joined:
    Sep 20, 2015
    Posts:
    169
    Hey everybody,
    I am working on the Unity Engine plugin and was having some trouble repeating the GUI background. After some research apparently there isn't an option for that, so I had to do some workaround.

    This is what I came up with:
    Code (CSharp):
    1. public static void DrawBGInRect(Rect rect, Texture2D texture)
    2. {
    3.     GUI.BeginScrollView(rect, Vector2.zero, rect, false, false, GUIStyle.none, GUIStyle.none);
    4.     GUIStyle style = new GUIStyle();
    5.     style.normal.background = texture;
    6.  
    7.     float size = texture.width;
    8.     float lastXPos = rect.x;
    9.     float lastYPos = rect.y;
    10.  
    11.     Rect tileRect = new Rect();
    12.     bool reachedEnd = false;
    13.     do
    14.     {
    15.         tileRect = new Rect(lastXPos, lastYPos, size, size);
    16.  
    17.         GUI.Label(tileRect, GUIContent.none, style);
    18.  
    19.         lastXPos += size;
    20.         if (lastXPos >= rect.width)
    21.         {
    22.             lastYPos += size;
    23.             if (lastYPos >= rect.height)
    24.             {
    25.                 reachedEnd = true;
    26.             }
    27.             lastXPos = rect.x;
    28.         }
    29.     }
    30.     while (!reachedEnd);
    31.     GUI.EndScrollView();
    32. }
    Really easy and simple solution, but it does the job, tho I was curious if there are any other better solutions to this problem. Does anyone have any ideas on this topic? Thanks in advance
     
    Last edited: Jun 6, 2019
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,692
    Looks fine to me. I'd probably just use that approach if it works!

    The only other way that occurs to me would be to have a RenderTexture that you render your repeating pattern to at the size/scale you need it, then render that one texture with a single call.
     
    Rukas90 likes this.