Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

How to auto scroll a scrollview when text gets bigger?

Discussion in 'Scripting' started by hs1S, Jan 5, 2010.

  1. hs1S

    hs1S

    Joined:
    Jul 23, 2009
    Posts:
    153
    How to auto scroll a scrollview when text gets bigger?

    Example (C#):

    Code (csharp):
    1.  
    2. Vector2 scrollPosition;
    3. int lines=0;
    4.    
    5. // The string to display inside the scrollview. 2 buttons below add  clear this string.
    6. String longString = "This is a long-ish string";
    7.  
    8.     public void OnGUI () {
    9.  
    10. scrollPosition = GUILayout.BeginScrollView (
    11. scrollPosition, GUILayout.Width (100), GUILayout.Height (100));
    12.  
    13. GUILayout.Label (longString);
    14.  
    15.  
    16. GUILayout.EndScrollView ();
    17.  
    18.  
    19. if (lines<=15){
    20.     longString += "\nHere is another line";
    21.         lines++;
    22.  
    23.     }
    24. }
     
  2. hs1S

    hs1S

    Joined:
    Jul 23, 2009
    Posts:
    153
    Tigeba on IRC post this code, and it works! We have to create a GUISkin.

    Code (csharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4.  
    5. public class Cliente : MonoBehaviour
    6. {
    7.         public GUISkin  mySkin;
    8.     Vector2 scrollPosition;
    9.     int lines=0;
    10.  
    11.     // The string to display inside the scrollview. 2 buttons below add  clear this string.
    12.     string longString = "This is a long-ish string";
    13.  
    14.     public void OnGUI()
    15.     {
    16.         GUI.skin = mySkin;
    17.  
    18.         GUIStyle bt = mySkin.GetStyle( "SmallText" );   // Get custom style from skin
    19.         scrollPosition = GUILayout.BeginScrollView( scrollPosition, GUILayout.Width( 200 ), GUILayout.Height( 100 ) );
    20.  
    21.         GUILayout.Label( longString, bt );
    22.  
    23.         GUILayout.EndScrollView();
    24.  
    25.  
    26.  
    27.        
    28.  
    29.         if( lines<=25 )
    30.         {
    31.             longString += "\nHere is another line";
    32.             lines++;
    33.  
    34.  
    35.  
    36.             GUIContent gc = new GUIContent( longString );
    37.             scrollPosition.y = bt.CalcHeight( gc, 100 ) - 100;  // Width is 100, and height is 100, so scroll any extra space.
    38.         }
    39.        
    40.         if (GUILayout.Button ("Add More Text"))
    41.         {
    42.             longString += "\nHere is another line";
    43.             GUIContent gc = new GUIContent( longString );
    44.             scrollPosition.y = bt.CalcHeight( gc, 100 ) - 100;  // Width is 100, and height is 100, so scroll any extra space.
    45.         }
    46.     }
    47. }
    48.