Note: I’m new to Unity and got thrown onto a project that’s developed around Unity.
I’m using a UnityWebRequest to get some JSON data which is then being parsed into a list of objects corresponding to a specific class, and then I display this on a UI.
I’m tasked with the following:
- Dynamically populate a dropdown containing some, but not all, fields of the class with user-friendly names (which fields should be determined in the class itself).
- A textbox to type in a string to search for instances of that class where the string value equals the value of the selected property in the dropdown.
- Filter the list of objects being displayed based on the above.
The fields for the class could change in the future, so the only place where changes should have to be made are in the class itself.
For example, I have the following two classes:
[Serializable]
public class CarData
{
public int carID;
public string carOwner;
public string makeName;
public string modelName;
}
[Serializable]
public class CarDataList
{
public List<CarData> CarList;
}
I parse my JSON data into the above like so:
CarDataList carDataList = JsonUtility.FromJson<CarDataList>(resultData); //where resultData is json data
Now, let’s say the user only wants carID
and carName
in the dropdown menu, but wants user-friendly names like ID
and Owner
.
Is there an easy way to do this? Currently, I created my own Attribute
class to put custom attributes onto each field such as a DisplayName
and IsRequired
attribute. I then loop through each field and check if IsRequired
is true, and if it is I add it’s DisplayName
to the dropdown menu. This seems like it’s harder than it should be.
If I use the above, then the search functionality is even more difficult. I would have to get the text of the selected dropdown item, compare it to each field’s custom attribute in the class to determine what field it corresponds to, and then use more reflection to get the name of that field before finally doing the actual filtering.
I come from an MVVM WPF background. I’m used to being able to bind dropdowns to an ObservableCollection
of objects, setting specific display names, etc., and getting the actual selected object back, not just an int value.
In Unity, it looks like I can’t do any of that easily.
Any advice would be greatly appreciated.