Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Why is my value able to go negative, when I thought I made it not able to?

I'm making a mana bar for a game. The value of mana is not supposed to be able to go lower than 0. I thought I stopped this with an if statement, but it still goes past. Here is the code.

wait(1)
print("Mana Overlay Launched")

--Variables
local player = game.Players.LocalPlayer
local character = player.Character
local hum = character.Humanoid -- Hum is equal to Humanoid
local over = script.Parent.Overlay
local label = script.Parent.ManaLabel
local mouse = player:GetMouse()

--Variable creation
local mana = Instance.new("IntValue")
	mana.Name = "Energy"
	mana.Parent = character
	mana.Value = 100

local maxmana = Instance.new("IntValue")
	maxmana.Name = "MaxEnergy"
	maxmana.Parent = character
	maxmana.Value = 100

if character.mana.Value <= 0 then
	character.mana.Value = 0
end

--Update function
function update()	
	local en = character.mana.Value / character.maxmana.Value
	label.Text = "mana (" .. math.floor(mana.Value) .. "/" .. maxmana.Value .. ")"	
	
	over:TweenSize(UDim2.new(en,0,1,0), "In", "Linear")
end

update()

character.mana.Changed:Connect(update)

--Add Mana Testing Function
mouse.KeyDown:Connect(function(key)
	key = key:lower()
	if key == "r" then
		character.mana.Value = character.mana.Value + 25
	end
end)

mouse.KeyDown:Connect(function(key)
	key = key:lower()
	if key == "t" then
		character.mana.Value = character.mana.Value - 25
	end
end)

4 comments

0

You need to put the if statement where you decrease the mana...

0

Yeah, I don't know if this is what you want, but I would do: if key == "t" and mana >= 25 then... that should prevent it from going to the negatives... hopefully lol

0

Ohhh. Thanks. I have new problem now though. The bar is obviously made to tween to either side when it increases or decreases. The value stays at 0, but the bar tweens past 0.

0

Nevermind! It's fixed due to Z_DC's answer. Thanks everyone!

2 answers

✓ Accepted answer

Since the if statement runs only once in the code provided due to it not being inside any function block, try putting the statement inside the update function:

function update()  
	if character.mana.Value < 0 then character.mana.Value = 0 end
    local en = character.mana.Value / character.maxmana.Value
    label.Text = "mana (" .. math.floor(mana.Value) .. "/" .. maxmana.Value .. ")"  

    over:TweenSize(UDim2.new(en,0,1,0), "In", "Linear")
end

key down is deprecated switch to user input service / context action plz

1 comment

0

i'm only using it to test the mana bar, as long as it works i don't care for now, since it won't be there in the final product

This discussion is preserved as it was. New answers, comments, and votes are closed.