- Home /
Show enum in a loop in on GUI
Hello I want too show my enum on a GUI button for each enum what would be best way of doing this a for loop or a foreach loop?
Answer by perchik · Apr 07, 2014 at 06:23 PM
I'd look at enum.GetNames if you're in C#
The example on that page is pretty much what you want to do, just iterate over all the names and make a button for each one.
EDIT 2: Replaced using System;
with using Enum = System.Enum;
to avoid using the whole system library
EDIT 1: Here's some code.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Enum = System.Enum;
public class Test : MonoBehaviour
{
public enum Shapes { Triangle = 3, Square = 4, Circle = 10 };
private Dictionary<string, bool> shapeBtnClicks;
void Start()
{
shapeBtnClicks = new Dictionary<string, bool>();
foreach (string name in Enum.GetNames(typeof(Shapes)))
{
shapeBtnClicks[name] = false;
}
}
void OnGUI()
{
foreach (string name in Enum.GetNames(typeof(Shapes)))
{
shapeBtnClicks[name] = GUILayout.Button(name);
}
if (shapeBtnClicks["Triangle"])
{
//Do something;
}
}
}
I'm in C# i'm still new to program$$anonymous$$g but i'll try my best and see if it works. would it work if i'm using an index with my enum?
Yep. you can loop over the names using GetNames or you can loop over the values(indices) by using GetValues
I think your answer is right but i'm having problems trying too make it work.
I would recommend to use System.Enum.GetNames
ins$$anonymous$$d of putting a using System;
at the top since the System namespace has some collisions with the UnityEngine namespace. Having both in a using statement can cause some issues. The most popular ones are:
System.Object <-> UnityEngine.Object
System.Random <-> UnityEngine.Random