Unity Lists



In this Unity C# tutorial you will create a custom visualization for arrays and lists in the editor.

Specify a space-separated list of assembly names as parameters for Unity to ignore on automatic updates. The space-separated list of assembly names is optional: pass the command line options without any assembly names to ignore all assemblies, as in example 1. Example 1 unity.exe -disable-assembly-updater Example 2. So in Unity I'm making Snake, and to do that I've a list which houses all the tail elements from the Snake (this was implemented by the NoobTuts tutorial on snake just FYI). I'm find with adding stuff and removing stuff from the list, HOWEVER, I do have an issue with part of the removal.

You will learn to
  • create a custom editor
  • use SerializedObject
  • manipulate a SerializedProperty that represents an array or list
  • use an enumeration for option flags
  • use GUI buttons

This tutorial comes after the Custom Data tutorial.

This tutorial is for Unity version 4.3 and above.

Creating Test Data

Unity's default way to show lists is serviceable, but it's possible to find yourself wanting for an alternative. The specifics can vary from case to case. So it would be useful if we could use a mix of different visualizations. It is possible to do this by adding attributes to variables that specify how the editor should show them.

We start with the finished Custom Data tutorial project, or by creating a new empty project and importing custom-data.unitypackage.

Unity Lists

Then we create a new test script named ListTester with some test arrays, and make a new prefab and prefab instance with it, so we can see it all works as expected.

Creating a Custom Inspector

Our first step to customizing our lists is to create a custom inspector for our test component. Create a new C# script named ListTesterInspector in the Editor folder, make it extend UnityEditor.Editor, and apply the UnityEditor.CustomEditor attribute to tell Unity that we want it to do the drawing for our component.
To actually change the inspector we need to override the OnInspectorGUI method of the Editor class. Leaving the method empty will result in an empty inspector as well.
There are three important differences between a property drawer and an editor. Firstly, in the editor we work with an entire SerializedObject instead of a single SerializedProperty. Secondly, an instance of the editor exists as long as the object stays selected, keeping a reference to its data instead of getting it via a method parameter. Finally, we can use EditorGUILayout, which takes care of positioning for us.

We can get to the serialized object via the serializedObject property. To prepare it for editing, we must first synchronize it with the component it represents, by calling its Update method. Then we can show the properties. And after we are done, we have to commit any changes via its ApplyModifiedProperties method. This also takes care of Unity's undo history. In between these two is where we'll draw our properties.

The fields are visible again, but they're empty. This is because PropertyField doesn't show any children – like array elements – unless we tell it to do so.

Creating an Editor List

To use a customized list in our inspector, we'll create an alternative for the PropertyField method. We will name this method Show and put it in its own static utility class, so we can use it wherever we want. We'll name this class EditorList and place it in the Editor folder.
This method doesn't do anything yet, but we can already use it in our custom editor, resulting once again in an empty inspector.
Showing a list consists of three parts, its foldout, its size, and its elements. We can show the foldout by using EditorGUILayout.PropertyField without having it show the children of the list. Then we can show the list elements ourselves with help of the arraySize property and the GetArrayElementAtIndex method of SerializedProperty. We'll leave the size for later.

Properly Indenting

We have our lists again, but their elements aren't indented. We can solve this by increasing the indent level before showing the elements, and decreasing it again afterwards.

Unity Lists Api

Now indentation works again, except for our color point list, which goes wrong after the first element. This is because we set the indent level to zero in our custom property drawer. There are two ways to fix this. Either our custom list should set the indent level to the correct value again after each element, or the property drawer should make sure it leaves the indent level unchanged. Let's make sure that ColorPointDrawer behaves well.

Collapsing Lists

Now that indenting works, we can take care of the next problem. Toggling the foldouts should collapse and expand the lists, but it currently doesn't work. This is easy to fix by checking the isExpanded property of our list.

Showing the Size

To show the list's size, we can use the special relative property named Array.size. We'll simply show it in between the foldout and the elements.

Customizing the List

Now that we have replicated the default list, it's time to add customizations. An easy start is to make the size that we just added optional. We add a boolean parameter to control this and turn it on by default.
Using this new option, we can switch of the size for some of our lists.
As a second option, let's make the list's label optional as well. If we don't show the label, we won't indent either and we will always show the elements, regardless whether the list is expanded.
Now we can remove the label from some of our lists.

Using Flags

While we can keep adding options this way, our method calls will become increasingly obscure. We could add wrapper methods with more descriptive names, but that would bloat our script and isn't flexible. An alternative is the use of option flags.

The first thing we need to do is create an enumeration of all our options. We name it EditorListOption and give it the System.Flags attribute. We place it in its own script file or in the same script as EditorList, but outside of the class.

Now we add entries for the two options that we already have. We also add an option for when we want nothing and for when we want the default. The default is to show both the list's label and its size. We specify this by combining both options with the bitwise OR operator |.
The boolean parameters of the Show method can now be replaced with a single options parameter. Then we'll extract the individual options with the help of the bitwise AND operator & and store them in local variables to keep things clear.
Then we can modify our custom inspector to use the new options approach.

Hiding the Element Labels

Another useful feature is the ability to hide the labels of the elements. So let's add an option for element labels and include it in the default. We can also add a convenient entry for the default without the element labels.
Unity Lists
Now all we have to do in our Show method is extract this option and perform a simple check. Let's also move the element loop to its own private method, for clarity.
Our element labels can now be hidden, but something is wrong when we use a narrower inspector. It turns out that our color point drawer still decides to use an additional line, but without a label this is no longer useful. The solution is simply to make sure ColorPointDrawer does not claim an extra line when it does not receive a label.

Adding Buttons

Instead of removing parts, we can also add thing to our list. We could add a set of buttons for manipulating list elements. They can provide an alternative way to delete and duplicate elements, and we can add a means to reorder the elements as well.

First we'll add an option for buttons, and also a convenient option to activate everything.

For the button labels we'll use a simple '+' for duplicate, a '-' for delete, and a '↴' (rightwards arrow with corner downwards) for move. You can directly insert the arrow unicode character, but I use its escape code just to be sure everyone can copy it correctly.

We predefine static GUIContent for these buttons and include handy tooltips as well. We also add a separate method for showing the buttons and call it after each element, if desired.

Unity Lists Api

Let's add these buttons to the lists for our color points and objects.
These buttons are way too large, because each claims an entire line. We want everything to stay together on a single line instead. We can instruct the automatic layout to do this by putting our content in between calls to EditorGUILayout.BeginHorizontal and EditorGUILayout.EndHorizontal.
That is a lot better, but the buttons are still too large. We'll change two things to make them behave. First, we'll apply some mini button styles to them. Second, we'll give them a fixed width of 20 pixels each.
Now the buttons look fine, but they don't do anything yet.

Fortunately, adding functionality to the buttons is very simple, as we can directly use the methods for array manipulation provided by SerializedProperty. We need the list and the current element index for this to work, so we add them as parameters to our ShowButtons method and pass them along inside the loop of ShowElements.

Our buttons now work as expected. Or do they? Try deleting an element from the objects list. If it references no component, it works. But if it does reference something, it will clear the reference, but not remove the element from the list.

While this is how Unity handles deletion in this case, it is weird. Instead, we want the element to always be removed, not sometimes cleared. We can enforce this by checking whether the list's size has remained the same after deleting the element. If so, it has only been cleared and we should delete it again, for real this time.

An additional button we could include is one to add an element when the list is empty. This is useful when we're not showing the list size, because in that case you could neither duplicate an element nor manipulate the list size directly. So let's add such a button.

Only Allowing Lists

What would happen if we would try to use our editor list with something that isn't a list at all? Let's find out by adding something to ListTester that is not a list.
It actually works for our integer. But it's not guaranteed to work for any arbitrary type and it will also result in errors for some options. It is a better idea to flatly refuse to show anything that isn't a list. So let's check whether the property is an array. If it isn't, we display a nicely formatted warning and nothing else.

Multi-object Editing

Another interesting point is multi-object editing. You can test this by duplicating our list tester object, make them a little different, and selecting both at the same time.
By default custom editors do not support multi-object editing, though that is easily fixed by adding the CanEditMultipleObjects attribute to our ListTesterInspector.
While this can be useful, it gets weird when you're editing multiple objects that have lists of different sizes. In general it is not very useful and might even be drawn wrong. So let's not show the list's elements when we have multiple different sizes.
We now have a generic list drawer with four customization options that you can use instead of the default list representation. Quite handy!

Downloads

Unity List Add

custom-list.unitypackage
The finished project.