Issue with lists

I’m trying to add some script variables to one list and change the variable value.

I’ve used the attached code.
My problem is that I can modify the TestBasicItem variable with no issue. But the itemList shows one element with null value.

I don’t understand why the list element show null value instead of showing the item1 value.

¿Can you explain me why this behavior happens?

Thank you very much!

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TestItemList1 : MonoBehaviour
{
    [SerializeField] public TestBasicItem item1;

    [SerializeField] public List<TestBasicItem> itemList;


    private void Update()
    {
        if(Input.GetKeyDown(KeyCode.T))
        {
            SetItem();
        }
    }

    private void SetItem()
    {
        itemList = new List<TestBasicItem>
        {
            item1
        };

        item1 = new TestWeaponItem("test", 2);

        Debug.Log("");
    }
}

public class TestBasicItem
{
    public string name;

    public TestBasicItem(string name)
    {
        this.name = name;
    }
}

public class TestWeaponItem : TestBasicItem
{
    public int value;

    public TestWeaponItem(string name, int value) : base(name)
    {
        this.value = value;
    }
}

Unity’s default serialization does not support polymorphism. You can achieve it via the ``[SerializeReference] attribute: Unity - Scripting API: SerializeReference

Otherwise this can work if the collection is marked non-serializable.

2 Likes

I see. It looks like combining the list with polymorphism is more tricky, but I’ll figure it out.
Thanks a lot!

The simplest workaround is to make TestBasicItem derive from ScriptableObject.

Unity can serialize polymorphic lists of any UnityEngine.Object-derived types.

2 Likes