unity3d SerializeField/Serializable不适用于自定义类列表(List< customClass>)

uemypmqf  于 2022-11-15  发布在  其他
关注(0)|答案(1)|浏览(151)

**问题:**我的自定义类(public List<ComponentClass> OnCast_Comp = new List<ComponentClass>();)列表没有出现在Unity编辑器中。我已经在它上面有[SerializeField],自定义类也在它上面有[System.Serializable]。但是它仍然没有出现在编辑器中。
法术持有者.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>();
}

单一拼字管理员.cs:

[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;
}

组件类.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);
    }
}
58wvjzkj

58wvjzkj1#

如果要在一个集合中保存不同类型的对象,则需要使用SerializeReference

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

相关问题