Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

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

Discussion in 'Editor & General Support' started by Stacklucker, Feb 21, 2022.

  1. Stacklucker

    Stacklucker

    Joined:
    Jan 23, 2015
    Posts:
    82
    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

    Code (CSharp):
    1. [System.Serializable]
    2. public class CustomIntClass
    3. {
    4.     public int CustomInt;
    5. }
    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.
     
  2. Stacklucker

    Stacklucker

    Joined:
    Jan 23, 2015
    Posts:
    82
    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.