Search Unity

  1. Unity 2019.2 is now released.
    Dismiss Notice

Create a GUI button for each line of text in a text file.

Discussion in 'Scripting' started by MH1, Sep 3, 2013.

  1. MH1

    MH1

    Joined:
    Mar 31, 2013
    Posts:
    7
    I want the first GUI button to display the first line, the second GUI button to display the second line, etc.
    I also want to be able to tell in the script (c#) witch button was clicked. Any Ideas?
     
  2. Eiznek

    Eiznek

    Joined:
    Jun 9, 2011
    Posts:
    371
    You'll have you use a stream reader or text reader basically. For the GUI it should be simple to add the buttons..

    Code (csharp):
    1.  
    2. public class AlterMyName : MonoBehaviour
    3. {
    4.     public List<TextObjects> readInFile = new List<TextObjects>();
    5.     void Awake()
    6.     {
    7.         for(int i = 0; i < 10; i++)
    8.         {
    9.             readInFile.Add(new TextObject("Test" + i, "Test" + i " + Value");
    10.         }
    11.     }
    12.    
    13.     void OnGUI()
    14.     {
    15.         Rect buttonRectDescending = new Rect(10, 10, 100, 50);
    16.         for(int i = 0; i < readInFile.Count; i++)
    17.         {
    18.             Rect buttonRectDescending = new Rect(10, 10+(i*55), 100, 50);
    19.             if(GUI.Button(buttonRectDescending, readInFile[i].myName))
    20.             {
    21.                 Debug.Log("Caught this Action" + readInFile[i].myName + " Value: " + readInfile[i].myValue)
    22.             }
    23.         }
    24.     }
    25.  
    26.     public class TextObjects
    27.     {
    28.         public TextObjects(string name, string val)
    29.         {
    30.             this.myName = name;
    31.             this.myValue = val;
    32.         }
    33.  
    34.         public string myName;
    35.         public string myValue;
    36.     }
    37. }
    38.  
    Side note.. I don't recommend using Unity GUI.. But its good for beginners.