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

My loop gives points way too fast even thought there is a wait. Why?

I am trying to make a script that when you touch a part you get 100 points but for 1. it doesn't see that there is a wait and it gives the points at the speed of light and 2. it does the loop for more than one time (witch is not suposed to happen)

Here is the script:

    for i = 1, 1, 1 do

wait(5)
game.Workspace.points.Touched:Connect(function()
    game.Players.walvie.leaderstats.points.Value = game.Players.walvie.leaderstats.points.Value + 100
end)
end

PS:game.Players.walvie.leaderstats.points.Value = game.Players.walvie.leaderstats.points.Value + 100 is on the same line.

2 answers

✓ Accepted answer

GENERAL PRACTICE

Your script will only work for your player, so you will want to define the player through the Player Event :GetPlayerFromCharacter() --- The player's character will be the hit.Parent

Your wait time can go into the function, rather than requiring a for-loop

ISSUES

You need a debounce to make sure the .Touched Event doesn't keep firing every time the part is touched (causing rapid gains after 5 seconds)

REVISED SERVER SCRIPT

local debounce = true

workspace.points.Touched:Connect(function(hit)
	if debounce == false then return end
	debounce = false
	local player = game:GetService("Players"):GetPlayerFromCharacter(hit.Parent)
	local points = player:WaitForChild("leaderstats"):WaitForChild("points")
	points.Value = points.Value + 100
	wait(5)
	debounce = true
end)

If you want the player to only ever receive the bonus once, you can just not reset the debounce

local debounce = true

workspace.points.Touched:Connect(function(hit)
	if debounce == false then return end
	debounce = false
	local player = game:GetService("Players"):GetPlayerFromCharacter(hit.Parent)
	local points = player:WaitForChild("leaderstats"):WaitForChild("points")
	points.Value = points.Value + 100
	wait(5)
end)
local buttonPressed = false
--Store whether the button is pressed in a local variable
 
game.Workspace.points.Touched:Connect(function(hit)
    if not buttonPressed then
    -- Is it not pressed?
 
        buttonPressed = true
        -- Mark it as pressed, so that other handlers don't execute
 
		game.Players.walvie.leaderstats.points.Value = game.Players.walvie.leaderstats.points.Value + 100
        -- Do Stuff
 
        buttonPressed = false
        -- Mark it as not pressed, so other handlers can execute again
    end
end)

From the Roblox Wiki with a few modifications to work for you.

2 comments

0

This only works for a user named "walvie" and not other players

0

I know, that's what they posted. I'm just assuming they're experimenting early on in their Lua learning and don't want to throw a truck-load of information.

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