Is there a better way of doing this script?

What the script is accomplishing is every time you jump, it gets rid of a coin. It does work but if you keep jumping, it gets rid of more coins than needed. Script is under StarterCharacterScripts

-- Variables ------------------------------
local Character = script.Parent
local Player = game.Players:GetPlayerFromCharacter(Character)
local Coins = Player.leaderstats.Coins
local debounce = false

-- Script ------------------------------
Character.Humanoid:GetPropertyChangedSignal("Jump"):Connect(function()
	if Character.Humanoid.Jump == true and Coins.Value >= 1 and debounce == false then
		debounce = true
		Coins.Value -= 1
		task.wait(0.5)
		debounce = false
	end
end)
local p=game.Players.LocalPlayer

local c=p.CharacterAdded:Wait()
local Coins = p.:WaitForChild("leaderstats"):WaitForChild("Coins")
local h:Humanoid=c:WaitForChild("Humanoid")
local d=false
h.Jumping:Connect(function(b)
	if b and Coins.Value>=1 then
		print("yes")
		Coins.Value-=1
	else
		print("no")
	end
end)

with debounce


h.Jumping:Connect(function(b)
	if b and Coins.Value>1 and not d then
		d=true
		print("yes")
		Coins.Value-=1
	else
		print("no")
	end
	wait(.5)
	d=false
end)

@BlockyMarco

I wouldn’t count a downgrade in readability as a better way of writing OP’s script

just add comments

Summary

This text will be hidden

besides instead of d==false use not d
instead of if Character.Humanoid.Jump == true use h.Jumping:Connect(function(b) if b

your script is good and easily readable
offtopic but still helpful: you can define a character type so you can get autocompletion for character when typing

type Character = Model & {Humanoid :Humanoid, HumanoidRootPart :Part} -- character type

-- Variables ------------------------------
local Character :Character = script.Parent
local Player = game.Players:GetPlayerFromCharacter(Character)
local Coins = Player.leaderstats.Coins
local debounce = false

-- Script ------------------------------
Character.Humanoid:GetPropertyChangedSignal("Jump"):Connect(function()
	if Character.Humanoid.Jump == true and Coins.Value >= 1 and debounce == false then
		debounce = true
		Coins.Value -= 1
		task.wait(0.5)
		debounce = false
	end
end)

and “If” it’s a local script then you can do local Player = game.Players.LocalPlayer

2 Likes

That is a pretty good tip :happy1: I will be using that in future projects! The script does work but after holding spacebar for a long time, it takes away extra coins. I will say the script is a server script

1 Like

I tested the script, but I cannot replicate this issue
maybe try checking if there are any other script which decrease the coins value