Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

SerializeField/Serializable doesn't work for list of custom class (List<customClass>)

Problem: my list of custom class (public List<ComponentClass> OnCast_Comp = new List<ComponentClass>();) doesn’t appear in the unity editor. I already have [SerializeField] above it, with the custom class having [System.Serializable] also above it. But it still wouldn’t show up in the editor.

SpellHolder.cs:

public class SpellHolder : MonoBehaviour
{
    // holds the currently owned spells for the player
    // only holds the spell, the content of the spell itself is inside SingleSpellManager.cs
    // [SpellHolder.cs] -> SingleSpellManager.cs

    [SerializeField]
    public List<SingleSpellManager> List_Spells = new List<SingleSpellManager>();
}

SingleSpellManager.cs:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[System.Serializable]
public class SingleSpellManager 
{
    // stores the magical components (MComp) of the spell 
    // SpellHolder.cs -> [SingleSpellManager.cs]

    [SerializeField]
    public List<ComponentClass> OnCast_Comp = new List<ComponentClass>();
    [SerializeField]
    public List<ComponentClass> OnHit_Comp = new List<ComponentClass>();

    [Header ("General Data")]
    public string spellName;
}

ComponentClass.cs:

// interface class
[System.Serializable]
public abstract class ComponentClass 
{
    public virtual void OnCast(){}
    public virtual void OnHit(){}

    //general info
    public string name = null;
    public string desc = null;

    //floats
    public float fl_a, fl_b, fl_c;

    //ints (can be used as types)
    public int int_a, int_b, int_c;

    //bools
    public bool bl_a, bl_b, bl_c;
}



// derivatives
[System.Serializable]
public class Projectile : ComponentClass
{
    // desc:
    // turns the spell into a projectile.

    public float power {get {return fl_a;}}
    
    public override void OnCast()
    {   // test
        UnityEngine.Debug.Log(power);
    }
}

>Solution :

You need use SerializeReference when you want to save different type of objects in one collection.

[System.Serializable]
public class SingleSpellManager 
{
    [SerializeReference]
    public List<ComponentClass> OnCast_Comp = new List<ComponentClass>();
    [SerializeReference]
    public List<ComponentClass> OnHit_Comp = new List<ComponentClass>();
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading