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

step on a brick and level up

I have a script to let me step on a brick and level up(leader stat). but the only problem is that it will do it infinitely and I only want it to do it once. how can I fix this? here is my script.

function onTouched(part)
	local h = part.Parent:findFirstChild("Humanoid")
	if (h~=nil) then
			local thisplr = game.Players:findFirstChild(h.Parent.Name)
			if (thisplr~=nil) then
				local stats = thisplr:findFirstChild("leaderstats")
				if (stats~=nil) then
					local score = stats:findFirstChild("Level")
                  if (score.value ~= 1)then
						score.Value = score.Value + 1
					end
				end
			end
		end
	end
script.Parent.Touched:connect(onTouched)

1 answer

✓ Accepted answer

The touched event fires several times when a player touches an object. It fires each time a different body part touches the brick and it may fire multiple times per body part depending on the player's movement on the part. To prevent giving a player multiple points, add the player name to a table after the point has been awarded and check to see if the player's name is in the table before awarding the point.

Additionally, your comparison to 1 in this statement if (score ~= 1)then will always be true because an IntValue is never equal to a number. The correct comparison is if (score.Value ~= 1) then

This code assumes a Script rather than a LocalScript, because the pointAwarded table would be recreated each time a player respawns if it is in a LocalScript. That wuld allow the player to collect the point again.

local pointAwarded = {}
function onTouched(part)
	local h = part.Parent:findFirstChild("Humanoid")
	if (h~=nil) then
		local thisplr = game.Players:findFirstChild(h.Parent.Name)
		if (thisplr~=nil) then				
			local stats = thisplr:findFirstChild("leaderstats")
			if (stats~=nil) then
				local score = stats:findFirstChild("Level")
				if (score.Value ~= 1) then
					if not pointAwarded[h.Parent.Name] then
						pointAwarded[h.Parent.Name] = true
						score.Value = score.Value + 1
					end
				end
			end
		end
	end
end
script.Parent.Touched:connect(onTouched)

1 comment

0

the score default is 1 so the script has to say ' if (score.Value ~= 2) then' now it should work!

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