I feel like I’m kind of having a brain fart, and that there must be a cleaner way to do this, but…

I want a method to apply damage to a stat, but if the damage exceeds the remaining stat left, the stat should be reduced to the minimum (0), but the remainder should be placed back into damage. (So it can be used later)
In addition, this should work with negative damage (e.i. healing) and the maximum value being the stat max instead.
Example: if health is at 5 and 7 damage is applied, the result should be 0 health and 2 damage remaining.
Mathf.Clamp() doesn’t work because it doesn’t return how much was, uh, clamped. So far, most of my attempts have been rife with messy conditionals. My latest attempt was to create a method with two ref inputs since two variables will change within the method.
Am I just being silly and overlooking something completely obvious?
My apologies if this doesn’t belong in this sub. Feel free to direct me elsewhere.
Add a check something like this
If (health < 0){ remaindingDamage = health * -1; }
this should effectively give you the positive number of the extra it took off
Oh and set your health = 0 for good measure
As a point of style, it might make sense to encapsulate the damage values into an object, and just pass that in for the method to act upon. Having functions with many ref or out params tends to be an indication of code-smell.
C# devs
null reference exceptions

source