Search Unity

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

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

  1. 13X


    Dec 31, 2012
    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


    Jun 2, 2009
    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;
    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


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