Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice
  3. Dismiss Notice

How can I split a multiline string into "pages"?

Discussion in 'Scripting' started by 13X, Jul 12, 2013.

  1. 13X

    13X

    Joined:
    Dec 31, 2012
    Posts:
    5
    What I want to do is split a multiline string (from a TextAsset), given a GUIStyle, into a string array so that each element of the array can fit into a rectangular boundary. I preferably want to do this with wordwrapping enabled in the GUIStyle.

    Essentially I'm trying to implement a quest log that displays a long piece of quest text in pieces that fit in the screen (page 1/6, 2/6 etc)

    E.g 1: Input is "1\n2\n3\n4n\" and using the calcheight method from the guistyle and the height of the rectangle I know that the rectangle can fit two lines of text, what I'm trying to do is return a string[] with elements {"1\n2", "3\n4"}, how could I split this up?

    E.g 2: Input is "abcde fghasdjf hga sjhfgsa jfg asdjfga ssjfgj sadgfj dg" with wordwrapping on this gets displayed as 3 lines of text which means the output string array should have 2 elements (because the rectangle can only fit 2 lines of text at a time). How would I know where to split the text?

    Thanks for taking the time to read my question :)
     
  2. tonyd

    tonyd

    Joined:
    Jun 2, 2009
    Posts:
    1,224
    The easiest method to fit text to a page is to use GUILayout and it's scroll view functions:

    Code (csharp):
    1. var pagesOfText : String;
    2. var border = 10;
    3. var scrollPosition : Vector2;
    4.  
    5. function OnGUI(){
    6.     GUILayout.BeginArea(Rect(border,border,Screen.width-border*2,Screen.height-border*2));
    7.      scrollPosition = GUILayout.BeginScrollView(scrollPosition, GUILayout.Width(Screen.width-border*2), GUILayout.Height (Screen.height-border*2));
    8.     GUILayout.Label(pagesOfText);
    9.     GUILayout.EndScrollView();
    10.     GUILayout.EndArea();
    11. }
    But if you want to manually fit content to a page, see the documentation on GUILayoutUtility.GetRect().
     
  3. 13X

    13X

    Joined:
    Dec 31, 2012
    Posts:
    5
    I'll try that out right now :) Thank you!