Search code examples
functionunity-game-enginescriptable-object

Unity: adding custom function to Scriptable Object


I want to add to my project CardSO - a scriptable object. I want to give it a name, points and for some cards a special behavior. how can I add a function to the SO field? for most of the cards, it can be empty (or just returning 0), I hoped I can write a function the takes List and return int. Any thoughts?

My current code layout:

using UnityEngine;

[CreateAssetMenu(fileName = "CardSO", menuName = "New CardSO", order = 0)]
public class CardSO : ScriptableObject
{
    public string name;
    public int points;
    public Sprite Sprite;
    
    // public int SpecialBehavior(List<CardSO>);
}

Thank You!


Solution

  • Well ... just implement it. If you need most cards without it why not have a base class and make the method virtual

    // Whatever shall be the default behavior
    public virtual int SpecialBehavior(List<CardSO> cards) => -1;
    

    and then make a special card child class that can override this method and return whatever you need

    [CreateAssetMenu]
    public class SpecialCardSO : CardSO
    {
        public override int SpecialBehavior (List<CardSO> cards)
        {
            // or whatever
            return cards.Length;
        }
    }