It is possible to do conditional serialization?

I wondering if is possible to do something like this.

[Serializable]
public class AnimationData
{
    /// some data
}


public class AnimatorDataController
{
    public int size;

    if(size>0)
    {
                //serialize an array
                public AnimationData[] animationData = new AnimationData[] { };             
    }
    else
    {
               //serialize one element only
               public AnimationData animationData = new AnimationData();
    }
 
}

is It possible? How to do it?
Thank you so much!!

No, you couldn’t change the declaring type of a member like that. You could mimic what Unity does though, serialize the array and expose properties that act the way you want. Like Renderer.material and Renderer.materials, where material is just a property that returns the first element of the materials array.

1 Like

Ok, thank you so much for your help!!

Note that it’s perfectly ok to store an array of one element, too. Which is basically the same as conditionally serializing “one or an array”.

2 Likes

Yes, i know it… but i want to have the opportunity to choose it from editor… it would be great!!

Hey!! Here i found somthimg very interesting!! Maybe is possible to do what i Want!! XD

1 Like

Using a custom inspector would allow you to selectively make it appear as a single property instead of an array with a length of one, definitely. That won’t change how the code works under the hood though.

2 Likes

You are right!!