Dynamically sized list of toggles in custom inspector?
In the custom inspector for a particular scriptableObject of type Thingy, I am trying to create a list of toggles that correspond to a list of scriptableObjects of type Foo.
public class Thingy : ScriptableObject
{
List<Foo> foos;
}
public class Foo : ScriptableObject
{
public int dataField;
public int anotherDataField;
//yada yada yada...
}
All Foos in the project are stored in a FooDatabase:
public class FooDatabase : ScriptableObject
{
List<Foo> fooList = new List<Foo>();
}
I want a toggle visible in the editor for each Foo in the FooDatabase. When the "Update Foos List" is clicked, I want to update the list of Foos in my Thingy to contain all the Foos which have their corresponding toggle selected and not contain any Foos which have their toggle selected. I thought using a ToggleGroup would be the best way to do this:
public class ThingyEditor : Editor
{
private Thingy thingy;
public FooDatabase fooDB;
void OnEnable()
{
thingy = (Thingy)target;
}
public override void OnInspectorGUI()
{
EditorGUI.BeginChangeCheck();
EditorGUILayout.BeginVertical();
EnableListOfFoosEdit();
EditorGUILayout.EndVertical();
if (EditorGUI.EndChangeCheck())
EditorUtility.SetDirty(target);
}
private class FooToggle
{
public Foo foo;
public bool toggleValue;
public FooToggle(Foo f, boot tv)
{
foo = f;
toggleValue = tv;
}
}
private void EnableListOfFoosEdit()
{
fooDB = (FooDatabase)EditorGUILayout.ObjectField("FooDatabase:", FooDB, typeof(FooDatabase), false);
List<Foo> foos;
List<FooToggle> fooToggles = new List<FooToggle>();
if (fooDB != null)
{
foos = fooDB.fooList;
foreach (Foo f in validFoos)
fooToggles.Add(new FooToggle(f, thingy.foos.contains(f));
bool fooToggleGroupEnabled = false;
fooToggleGroupEnabled = EditorGUILayout.BeginToggleGroup("Foos: ", fooToggleGroupEnabled);
foreach (FooToggle ft in fooToggles)
fooToggleGroupEnabled = EditorGUILayout.Toggle(ft.foo.name, foo.toggleValue);
EditorGUILayout.EndToggleGroup();
}
if(GUILayout.Button("Update Foos List"))
{
foreach (FooToggle ft in fooToggles)
{
if(f.toggleValue == true)
{
if(!thingy.foos.Contains(f))
{
thingy.foos.Add(f);
}
}
else if(f.toggleValue == false)
{
if (thingy.foos.Contains(f))
{
thingy.foos.Remove(f);
}
}
}
}
}
}
With my current code all I am doing is displaying the header toggle for the toggle group. Can anyone help me out?
Your answer
Follow this Question
Related Questions
Update gameObject's children properties from CustomEditor class 1 Answer
Adding space() to BeginHorizontal() causes extra vertical spacing after certain amount. 1 Answer
Custom Editor List with child classes 1 Answer
How do I use EditorGUILayout.EnumPopup with an enum with 'holes' in a custom inspector. 3 Answers
Assigning multiple assets to multiple variables on inspector 1 Answer