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

How to detect if and which player hit a certain part?

Asked by 10 years ago

I need to detect if a player hit a part and then get that player and award them a "Star" in my game.

So far I've tried the code below, which gives the star(s) to every player in the game.

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

I tried some other things but they didn't work, this is the closest I've gotten.

Any amount of help is appreciated very much.

0
Currently trying with a click detector instead. FierceByte 25 — 10y

1 answer

Log in to vote
1
Answered by
jakedies 315 Trusted Moderation Voter Administrator Community Moderator
10 years ago
script.Parent.Touched:connect(function(hit)
    --We get the player using the GetPlayerFromCharacter method which returns the player based on the character. If hit is not nil (or false) and hit.Parent is not nil (or false) we set the player variable to what that method would return
    local player = hit and hit.Parent and Game.Players:GetPlayerFromCharacter(hit.Parent);
    --If it was an actual player that touched the part
    if player then
        --We check if they have a leaderstats object, if so we assign stats variable to find the Stars object in leaderstats
        local stats = player:FindFirstChild("leaderstats") and player.leaderstats:FindFirstChild("Stars");
        --If leaderstats.Stars exist
        if stats then
            --Increment it
            stats.Value = stats.Value + 1;
        end
    end
end);
0
If you want to use a click detector, it conveniently gives you the player directly so you can just add to the Stars value directly instead of getting their player first. jakedies 315 — 10y
0
Please don't just post code, explain what you did and why you did it to the asker. Perci1 4988 — 10y
0
I actually did edit my code to add comments to most of the lines but I guess I didn't publish. Let me re-do it. jakedies 315 — 10y
0
It works! Thanks you so much. FierceByte 25 — 10y
View all comments (2 more)
0
Another question, how do I make it so it only gives the point once before doing something else? FierceByte 25 — 10y
0
Well you could insert anyone who already got the point into a table, and if they are in the table you know they got the point so you can handle it like that. jakedies 315 — 10y
Ad

Answer this question