How to make my own operation with my classes

Hi, I have a question, I made this class:

public class BonusMaxValue {

    [SerializeField] float _maxValue = 0;

    protected float bonus = 0;

    public float maxValue { get { return _maxValue + bonus; } }

    public Action<float> OnMaxValueBonusChanged;

    public void SetBonus(float amount)
    {
        bonus = amount;
        OnMaxValueBonusChanged?.Invoke(amount);
    }

    public void AddBonus(float amount)
    {
        bonus += amount;
        OnMaxValueBonusChanged?.Invoke(amount);
    }

    public void RemoveBonus(float amount)
    {
        bonus -= amount;
        OnMaxValueBonusChanged?.Invoke(amount);
    }

    public void AddMultiplierBonus(float multiplier)
    {
        float amount = (_maxValue * multiplier) - _maxValue;
        bonus += amount;
        OnMaxValueBonusChanged?.Invoke(amount);
    }

    public  void RemoveMultiplierBonus(float multiplier)
    {
        float amount = (_maxValue * multiplier) - _maxValue;
        bonus -= amount;
        OnMaxValueBonusChanged?.Invoke(amount);
    }
}

and I would like to multiply this classe by another or by a float to get the multiplication of the float and the maxValue. I saw in unity this line of code for Vector3 class:

public static Vector3 operator *(float d, Vector3 a);

So I think, it’s possible to do it but I don’t know how does it work.

You need to overload the operators. Here’s how to do it: Operator overloading - Define unary, arithmetic, equality, and comparison operators. - C# reference | Microsoft Learn

1 Like

Thank you, I am going to take look at this

I will go with one method with two parameters one “ammount” other “multiplier” so you get rid of too many methods what do same thing.THen you dont need add end remove and in that case you just pass mulitlier 0.Or even add 3rd parameter for operation so you can have every operation in one method and change only in if statement

public class UnityForum : MonoBehaviour
{
    float bonus = 0;
    public enum Operations {Add,Remove,Set}

    public void ChangeBonus(Operations operation, float amount, float multiplier)
    {
        if(operation.Equals(Operations.Add))
        {
            bonus += amount;
        }
        if(operation.Equals(Operations.Remove))
        {
            bonus -= amount;
        }
        else if(operation.Equals(Operations.Set))
        {
            bonus = amount;
        }
        OnMaxValueBonusChanged?.Invoke(amount);
    }
}