Attribute Clamping

  1. What do you want to achieve? I want to be able to clamp a number so it doesn’t go into the negatives

  2. What is the issue? I’ve recently started working with Attributes and I’m unsure of how to clamp it

  3. What solutions have you tried so far? I looked for solutions, on the API and a lot of attempts at making it work myself but I cannot figure it out.

My old code using values inside the player worked fine:

HungerInt.Value -= math.clamp(decreaseamount,0,InitialHungerStatInt.Value)

But with Attributes I don’t know how to do this. Here is a failed example (I don’t want to salvage it because I’m pretty sure it’s formatted wrong anyway.)

player.Character:SetAttribute(“Hunger”, math.clamp(decreaseamount, 0,player.Character:GetAttribute(“InitialHunger”))

It sets the player hunger to 1 instead of decreasing it by 1. I’m not sure how to separate the attribute value and then decrease it like I would with an IntValue. Any clear solutions/help would be extremely appreciated.

The clamp should work fine, its just that you didnt exactly subtract the Hunger attribute with the clamped number.

You should GetAttribute("Hunger") then subtract it with the clamped number

You should also use variables since it does get kinda messy when working with attributes

local hunger = player.Character:GetAttribute("Hunger")
local initHunger = player.Character:GetAttribute("InitialHunger")

player.Character:SetAttribute("Hunger", hunger - math.clamp(decreaseamount, 0, initHunger))

A friend helped and explained the problem after I posted*, and this was the exact solution as well!

Thank you for typing this out !