its not decreasing the amount of the energy someone can please explain me why my code not working?
-- ServerScriptService > EnergySystem
local Players = game:GetService("Players")
local RunService = game:GetService("RunService")
local EnergyRechargeZone = workspace:WaitForChild("EnergyRechargeZone")
local ENERGY_DECREASE_AMOUNT = 1
local ENERGY_RECHARGE_RATE = 1
local MIN_ENERGY = 5
local MAX_ENERGY = 100
local ENERGY_DECREASE_AMOUNT = 1
local MIN_ENERGY = 5
local MAX_ENERGY = 100
local function monitorEnergy(player)
local energyStat = player.leaderstats:FindFirstChild("Energy")
while true do
wait(math.random(1, 4)) -- Random wait between 1 and 4 seconds
local humanoid = player.Character and player.Character:FindFirstChild("Humanoid")
if humanoid and humanoid.MoveDirection.Magnitude > 0 and energyStat.Value > MIN_ENERGY then
energyStat.Value -= ENERGY_DECREASE_AMOUNT
print(energyStat.Value)
end
end
end
local function checkRechargeZone(player)
RunService.Heartbeat:Connect(function()
if player.Character then
local hrp = player.Character:FindFirstChild("HumanoidRootPart")
if hrp and (hrp.Position - EnergyRechargeZone.Position).Magnitude < EnergyRechargeZone.Size.X then
player.leaderstats.Energy.Value = math.min(player.leaderstats.Energy.Value + ENERGY_RECHARGE_RATE, MAX_ENERGY)
end
end
end)
end
Players.PlayerAdded:Connect(function(player)
player.CharacterAdded:Connect(function()
monitorEnergy(player)
checkRechargeZone(player)
end)
end)
Is it decreasing more than one, or not decreasing at all?
If it’s decreasing more than 1, it’s because you are calling monitorEnergy() every time a character is added
Same thing with checkRechargeZone()
To fix it, maybe do something like
local function hello(player)
local character = player.Character
while true do
if not character then --Add these 3 lines so that if the player dies, it can detect it and stop the loop
break
end
--Code
end
end
game.PlayerAdded:Connect(function(player)
player.CharacterAdded:Connect(function()
hello(player)
end)
end)
Something you might want to do also is changing the type of Energy from numValue to intValue. You would be sure that you don’t get decimals as a value.
Here, I think this is why.
The reason why its not working is because you are checking for move direction on the server, it is returning a 0.
Solution:
Add a local script in the starter gui or smt like that, then add a remote event under the local script
and write this in the local script:
game.Players.LocalPlayer.Character:WaitForChild('Humanoid',999)
local running = false
game:GetService('RunService').Heartbeat:Connect(function()
if game.Players.LocalPlayer.Character:WaitForChild('Humanoid',999).MoveDirection.Magnitude > 0 then
if running == false then
running = true
script.RemoteEvent:FireServer(1)
end
else
if runnin == true then
running = false
script.RemoteEvent:FireServer(2)
end
end
end)
Then just implement the remote receiving in the server script and it should work (Just don’t use move direction on the server side)