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

Why when the player touches this it adds a coin to himself and the other players?

Asked by 10 years ago

This is a leaderboard and the leaderboard in the leaderboard there is coins so I made a part when Touched it will give the player 1 coin but when he touches it, it gives him and the other players 1 coin I want to stop that help please!

player = script.Parent.Parent.Parent


script.Parent.Touched:connect(function()
    for _,Player in pairs (game.Players:GetPlayers()) do
        if Player:FindFirstChild("leaderstats") then
            Player.leaderstats.Coins.Value = Player.leaderstats.Coins.Value +1
        end
    end
    script.Parent:remove()
end)


0
Your question literally makes no sense. NoahWillCode 370 — 10y
0
Wait i'll edit it chill22518 145 — 10y
0
Done chill22518 145 — 10y

2 answers

Log in to vote
1
Answered by 10 years ago

The problem is that you're looping through all of game.Players children and checking and giving points to everyone. The following code will check to see if the brick is being touched by a player, and, if so, give points to him and him alone.

script.Parent.Touched:connect(function(hit)
    local plrHit = game.Players:GetPlayerByCharacter(hit.Parent)
    if plrHit and plrHit:FindFirstChild("leaderstats") then
        plrHit.leaderstats.Coins.Value = plrHit.leaderstats.Coins.Value + 1
    end
end)
0
K thanks chill22518 145 — 10y
0
Didn't work chill22518 145 — 10y
Ad
Log in to vote
1
Answered by
Perci1 4988 Trusted Moderation Voter Community Moderator
10 years ago

This is a leaderboard and the leaderboard in the leaderboard there is coins so...

What? I don't really care about grammar but please use enough so we can understand you.

Anyways, your problem should be obvious. You're looping through all the players with a for loop, so of course it will affect all of them. Also what is your player variable? You never use it. It obviously cannot be a player, since this script has to be in a part to function at all. You also never have any check to make sure the part that hit the brick is actually a player, and not just some random part. Try something like this:

script.Parent.Touched:connect(function(hit)
    if game.Players:GetPlayerFromCharacter(hit.Parent) then --Makes sure it's a real player
        local player = game.Players:GetPlayerFromCharacter(hit.Parent)
        if player:FindFirstChild("leaderstats") then
            player.leaderstats.Coins.Value = player.leaderstats.Coins.Value + 1
        end
        script.Parent:Destroy() --Remove() is deprecated, so use Destroy() instead. 
    end
end)

Answer this question