Hi everyone, I want to put a list of if statements into a format similar to the way I have my buttons. But I’m not sure how. I would like to declare a bunch of them in a list but I don’t think you can make a list of if statements.
using UnityEngine;
using System.Collections;
public class SomeGUI : MonoBehaviour {
public string[] someText;
void OnGUI () {
someText= new string[] {"Text1","Text2","Text3","Text4","Text5","Text6"};
for(int i = 0; i < someText.Length; i++){
//list of if statements
if(GUILayout.Button(someText*, GUILayout.Width(142), GUILayout.Height(25))){*
}
You can use a switch statement:
switch(i) {
case 0 :
// Do for 0
break;
case 1:
// Do for 1
break;
case 2:
// Do for 2
break;
default:
// Do for everything else
break;
}
In that case I think you are looking for something like the following:
for (int i = 0; i < someText.Length; ++i) {
if (GUILayout.Button(someText*, GUILayout.Width(142), GUILayout.Height(25))) {*
// If button was clicked change value of someInt (aka index of button).
someInt = i;
}
}
If you don’t mind getting a little fancy with .NET and C# you could do something like this:
using System;
using UnityEngine;
using System.Collections.Generic;
public class GUIScript : MonoBehaviour
{
public class TextButton
{
public Rect Position;
public string Text;
public Action Action;
}
List<TextButton> _textButtons;
// Use this for initialization
void Start ()
{
_textButtons = new List<TextButton> ();
_textButtons.Add (new TextButton { Position = new Rect (0, 0, 50, 50), Text = "text1", Action = () =>
{
// do whatever you would do when button 1 is hit
}});
_textButtons.Add (new TextButton { Position = new Rect (0, 75, 50, 50), Text = "text2", Action = () =>
{
// do whatever you would do when button 2 is hit
}});
}
// Update is called once per frame
void Update ()
{
}
void OnGUI ()
{
foreach (TextButton textButton in _textButtons)
if (GUI.Button (textButton.Position, textButton.Text))
textButton.Action ();
}
}