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

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

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.

1 comment

0

Currently trying with a click detector instead.

1 answer

✓ Accepted answer
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);

6 comments

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.

0

Please don't just post code, explain what you did and why you did it to the asker.

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.

0

It works! Thanks you so much.

0

Another question, how do I make it so it only gives the point once before doing something else?

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.

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