David K
David K

Reputation: 31

Serializable class Initialized values are ignored || Unity C#

The problem is the following:

I don't know the ins and outs of the Unity Serializer, could anyone help me with this predicament?

Kind Regards,

David

-ScreenShot Code https://i.sstatic.net/Ct5uC.png

[CreateAssetMenu(fileName = "ImagesWithKeys", menuName = "ScriptableObjects/Images With Keys")]
public class ImagesWithKeysScriptableObject : ScriptableObject
{
    public ImageWithKeyModel[] ImagesWithKeys;
}



[Serializable]
public class ImageWithKeyModel
{
    public string Key = "23";
    public Sprite ImageToUse;
    public Color ColorToUse = new Color(1, 1, 1, 1);
}

-Screenshot Unity https://i.sstatic.net/HAXOo.png

enter image description here

Upvotes: 0

Views: 2134

Answers (1)

Gunnar B.
Gunnar B.

Reputation: 2989

(Not really an answer, but too long for comments.)

I suppose you inserted those elements by increasing the size of the array in the inspector?

I don't exactly know what happens internally, but this doesn't seem to initialize your custom class. If you put

private void OnEnable()
{
    ImagesWithKeys = new ImageWithKeyModel[5];
}

into your scriptable object, this will initialize them like expected (e.g. white color).

If you initialize it like above with at least one element, it will remember the default values, even if you change the size of the array in the inspector (decreasing and increasing) for as long as you don't set it to 0. If you do that, adding will result in not initialized elements again.

Edit:
Also I noticed that the constructor (added one to the custom class containing a Debug.Log) is actually called twice with the above code. If you add via the inspector, it's only called once (as one would expect). Seems like there is some actual assignment happening between those two calls.

Upvotes: 1

Related Questions