- Home /
C# Displaying a List in Series
Hi everyone, I've been try to make a list be displayed in series of five. But I'm not sure how. When I click on one of the GUI.Buttons I would like it to display the next/previous five elements of stringList. I think I need a for loop but I'm not sure where to go from here.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class NewBehaviourScript : MonoBehaviour {
public List<string> stringList = new List<string>();
// Use this for initialization
void Start () {
for (int i = 0; i < 20; i++)
stringList.Add("Something"+i.ToString());
}
// Update is called once per frame
void OnGUI () {
if (GUI.Button(new Rect(10, 10, 50, 50), "Forward"))
//Go up the next series of five
for (int i = 0; i < 20; i++)
Debug.Log(stringList[i]);
if (GUI.Button(new Rect(10, 70, 50, 30), "Backward"))
for (int i = 0; i < 20; i++)
//Go down the next series of five
Debug.Log(stringList[i]);
}
}
Comment
Best Answer
Answer by Ettax1 · Aug 25, 2013 at 07:49 AM
Hello DangerousBeans, I fixed your code so it should print 5 element at time. I hope this help you to understand how it can be done. :)
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class NewBehaviourScript : MonoBehaviour
{
public List<string> stringList = new List<string>();
//Current page
private int page = 0;
// Use this for initialization
void Start ()
{
for (int i = 0; i < 20; i++)
stringList.Add("Something"+i.ToString());
}
void OnGUI ()
{
//Max elements per page
const int MAX = 5;
if (GUI.Button(new Rect(10, 10, 50, 50), "Forward"))
{
if(page + MAX < stringList.Count)
page += MAX;
//Go up the next series of five
for (int i = 0; i < MAX; i++)
Debug.Log(stringList[i + page]);
}
if (GUI.Button(new Rect(10, 70, 50, 30), "Backward"))
{
if(page - MAX > 0)
page -= MAX;
else
page = 0;
//Go down the next series of five
for (int i = 0; i < MAX; i++)
Debug.Log(stringList[i + page]);
}
}
}
Answer by robertbu · Aug 25, 2013 at 07:43 AM
Here is some addition to your code to display lines:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Lines : MonoBehaviour {
public List<string> stringList = new List<string>();
public int lines = 5; // Number of lines to display
private string displayString;
private int startIndex = 0;
void Start () {
for (int i = 0; i < 23; i++)
stringList.Add("Something"+i.ToString());
BuildString();
}
// Update is called once per frame
void OnGUI () {
if (GUI.Button(new Rect(10, 10, 150, 50), "Forward")) {
if (startIndex + lines < stringList.Count) {
startIndex += lines;
BuildString();
}
}
if (GUI.Button(new Rect(10, 70, 150, 50), "Backward"))
if (startIndex - lines >= 0) {
startIndex -= lines;
BuildString();
}
GUI.Label(new Rect(200,10,150,100), displayString);
}
void BuildString() {
displayString = "";
for (int i = startIndex; i < Mathf.Min(startIndex + lines, stringList.Count); i++) {
displayString += stringList[i] + "\n";
}
}
}