Home > database >  How to call functions or classes to override existing functions?
How to call functions or classes to override existing functions?

Time:07-27

I'm creating a card game where each card has its own function. I have all my database created in ScriptableObjects. So I call these OS in the "CardBG" class and add some virtual functions

public class CardBG : MonoBehaviour

   protected virtual void OnDamage()
    {
    }
    
    protected virtual void OnDie()
    {
    }
    
    protected virtual void OnAttack()
    {
    }
    
    protected virtual void OnEndTurnP1()
    {
    }

My idea is to create a script for each card that will override these "CardBG" functions. The problem is that initially I tried to add this script in the OS, but it doesn't seem possible. So I don't know a way to call these scripts for each different letter.

CodePudding user response:

You can't assign component references to scriptable object asset fields, but you can do the reverse: assign scriptable object assets to component fields.

So what you could do is reverse things and move your virtual methods and their overrides into scriptable objects. Then when for example OnDamage is called on your card component, it could call the corresponding method in whatever scriptable object has been assigned to it and pass itself as an argument.

public class CardComponent : MonoBehaviour
{
    public Card card;
    public float health;
    
    public void OnDamage() => card.OnDamage(this);
    public void OnDie() => card.OnDie(this);
    public void OnAttack() => card.OnAttack(this);
    public void OnEndTurnP1() => card.OnEndTurnP1(this);
}

public abstract class Card : ScriptableObject
{
    public virtual void OnDamage(CardComponent component) { }
    public virtual void OnDie(CardComponent component) { }
    public virtual void OnAttack(CardComponent component) { }
    public virtual void OnEndTurnP1(CardComponent component) { }
}

[CreateAssetMenu]
public class BossCard : Card
{
    public override void OnAttack(CardComponent component) => component.health -= 10000;
}
  • Related