- Home /
Best way to combine GUI.Toggles and Flaged Enum
Hi basically I'm using [Flag] enum's to determine the allowed options for some objects e.g what types of objects there allowed to target. I'm trying to expose these options to the user so they can decide how they want the object to function. since I want it to be possible to have multiple options on at a time the only obvious GUI option is GUI.Toggle
however to use them I'm having to use the following code that seam far to long winded as i have to convert the enum to an array of bools but I'm sure there's an easier way but I cant seam to find it.
//enum setup
[Flags]
public enum MyEnum
{
Group1 = 1,
Group2 = 2, //etc
//get the current enum setup into the bools
for(int i = 0; i < 10; i++) //assuming 10 items in the enum
bools[i] = ((enumInstance & (MyEnum) Mathf.Pow(i,2)) == (MyEnum) Mathf.Pow(i,2));
//user gui options and save any changes
bool changed = false;
for (int j = 0; j < 10; j++)
{
bool temp = bools[i];
bools[j] = GUI.Toggle (new Rect (220, (Screen.height - 190) + (15 * (j)), 100, 15), bools[j], ((TurretGroup)Mathf.Pow (2, j)).ToString ());
if(selectedgroup[j] != temp)
changed = true;
}
if(changed)
{
object.enumInstance = 0;
for(int k = 0; k < 10; k++)
if(bools[k])
object.enumInstance = object.enumInstance | (TurretGroup)Mathf.Pow (2, k);
}
Answer by Bunny83 · Jun 10, 2011 at 10:37 AM
You could do it that way:
TurretGroup enumInstance;
private TurretGroup ChangeFlag(TurretGroup aOldValue, TurretGroup aFlag, bool aState)
{
return (aState)?aOldValue | aFlag:aOldValue & ~aFlag;
}
private void OnGUI()
{
for (int j = 0; j < 10; j++)
{
TurretGroup currentItem = (TurretGroup)(1<<j); // Much faster than Mathf.Pow
enumInstance = ChangeFlag(enumInstance,currentItem,
GUI.Toggle (new Rect (220, (Screen.height - 190) + (15 * (j)), 100, 15), ((int)enumInstance & (1<<j)) > 0, (currentItem).ToString ()));
}
}
Another way would be to use your own guistyles for on/off
TurretGroup enumInstance;
GUIStyle flagOn;
GUIStyle flagOff;
private void OnGUI()
{
for (int j = 0; j < 10; j++)
{
TurretGroup currentItem = (TurretGroup)(1<<j); // Much faster than Mathf.Pow
GUIStyle style = ((int)(enumInstance & currentItem)>0)?flagOn:flagOff;
if (GUI.Button(new Rect (220, (Screen.height - 190) + (15 * (j)), 100, 15), (currentItem).ToString (),style))
{
enumInstance = enumInstance ^ currentItem;
}
}
}
Your answer
Follow this Question
Related Questions
Using an Enum for GUI.Toggle? 1 Answer
Pause Button Problems 2 Answers
EnumPopup in Javascript? 2 Answers
change the style of a gui by a key press 0 Answers
Toggle and Skin 1 Answer