Adding custom serializable class to array in property drawer links elements.

I understand that adding a new element to an array or list inside a property drawer using “InsertArrayElementAtIndex” or even increasing the size of the array by one duplicates the last entry of that array. That is how Unity serialization works.

What I don’t understand is why some of my classes are not only getting duplicated, but are essentially linked/joined afterwards, meaning manipulating the data inside of the elements of the List/Array also overwrites the same change in all my other elements.

Testing this with a simple class like

[System.Serializable]
public class CustomIntClass
{
    public int CustomInt;
}

does NOT link it (only duplicates the last entry as expected), but with some more complex classes I do get the linking issue and I’m not sure what is causing this, hence this thread.

After struggling for months with this kind of issue I figured out what the cause is.

Unity decided (for performance benefits of the editor but arguably frustration and madness for the developer) to reuse the SAME property drawer instance for elements in a list. Using reorderable lists makes this particularly painful because one has to access cached variables inside the reorderable lists callback functions.

Great documentation on this one guys.

For anyone running into the same issue, the solution is to cache the respective drawer instance’s data in a dictionary keyed with the property’s property path.