Join Jesse Freeman for an in-depth discussion in this video Variable limitations in the Inspector, part of Building Custom Tools to Extend the Unity IDE.
- [Voiceover] While Unity does a great job of exposing some commonly used types, there are some limitations. Let's go back into our HelloWorld script and take a look at some more complex types of collections. At the top of our class, let's import the System.Collections.Generic namespace. This will give us access to collection types like list and dictionary. We'll start with the commonly used collection list. A list is similar to an array, but it allows you to dynamically add and remove elements at runtime, versus an array, which is usually set at a fixed size.
Let's create a public List. We'll give it a type of String, and call it stringList. We'll save our class and go back into Unity. You'll notice that our stringList will appear in our inspector. Just like our arrays, it has a size. Let's set this to three, and we can add text. We can also remove these elements by lowering the size value. List works exactly like arrays in the inspector.
Let's take a look at something a little bit more complicated. Going back into our code, let's add a public field for a Dictionary. A Dictionary allows us to store data in a key value pair. In this case, we're going to make the key a String and the value a Vector3. Here, we'll call this childrenPositions. Let's save this and go back into the inspector. As you can see, our dictionary isn't going to automatically show up in the inspector. The same limitation revolves around properties on a class.
A property is like a field, but it involves using a getter and setter. Here, we'll create a public int property called life, and inside of it, we'll create a getter and setter. C# automatically resolves this and makes it act like a field. Properties are useful when you want to do additional logic on a particular field. For this case, let's say we want to make sure that if life ever gets below zero, that we automatically call a method kill.
In this case, we can add logic to the setter to monitor the values that go into life. If we save our code and go back to Unity, you'll notice that fields don't automatically get exposed in the inspector. It's important to keep some of these limitations in mind, especially when it comes to building out more complicated classes. When it comes to these types of limitations, we're going to have to build custom inspector fields in order to expose that data to the editor.
- Exposing variables to the Inspector
- Providing attributes to Inspector fields
- Extending the base editor
- Creating custom UI elements
- Modifying the layout of a custom editor
- Building a custom window
- Saving and loading data
- Creating a reorderable list
- Skinning custom inspectors
- Exporting assets as Unity packages