Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

step on a brick and level up

Asked by 11 years ago

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.

01function onTouched(part)
02    local h = part.Parent:findFirstChild("Humanoid")
03    if (h~=nil) then
04            local thisplr = game.Players:findFirstChild(h.Parent.Name)
05            if (thisplr~=nil) then
06                local stats = thisplr:findFirstChild("leaderstats")
07                if (stats~=nil) then
08                    local score = stats:findFirstChild("Level")
09                  if (score.value ~= 1)then
10                        score.Value = score.Value + 1
11                    end
12                end
13            end
14        end
15    end
16script.Parent.Touched:connect(onTouched)

1 answer

Log in to vote
1
Answered by
AxeOfMen 434 Moderation Voter
11 years ago

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.

01local pointAwarded = {}
02function onTouched(part)
03    local h = part.Parent:findFirstChild("Humanoid")
04    if (h~=nil) then
05        local thisplr = game.Players:findFirstChild(h.Parent.Name)
06        if (thisplr~=nil) then             
07            local stats = thisplr:findFirstChild("leaderstats")
08            if (stats~=nil) then
09                local score = stats:findFirstChild("Level")
10                if (score.Value ~= 1) then
11                    if not pointAwarded[h.Parent.Name] then
12                        pointAwarded[h.Parent.Name] = true
13                        score.Value = score.Value + 1
14                    end
15                end
16            end
17        end
18    end
19end
20script.Parent.Touched:connect(onTouched)
0
the score default is 1 so the script has to say ' if (score.Value ~= 2) then' now it should work! chabad360 34 — 11y
Ad

Answer this question