So basically I've always had trouble finding the player while making a few games. Right now I'm trying to make a game where one player can use a tool to summon a block and when that block hits another player it damages them. How I'm finding the player right now is really convoluted and I feel there is probably a much easier way. What I'm doing to get the player is making it so that when a player joins, a StringValue records their name and then I get that name from the StringValue by using FindFirstChild in ReplicatedStorage (where the StringValue is located). Here's the script:
game.Players.PlayerAdded:connect(function(player) local stat = Instance.new("StringValue", game.ReplicatedStorage) stat.Name = "NameVal" stat.Value = player.Name end)
and here's the script for when the player is hit with the block:
local part = script.Parent local name = game.ReplicatedStorage:FindFirstChild("NameVal").Value local player = game.Players:FindFirstChild(name) local char = game.Workspace:WaitForChild(name) function onTouch(hit) if hit.Parent:FindFirstChild("Humanoid") then if hit.Parent:FindFirstChild("Humanoid") == char.Humanoid then return end hit.Parent:FindFirstChild("Humanoid").Health = hit.Parent:FindFirstChild("Humanoid").Health - 10 else return end end part.Touched:connect(onTouch)
Please inform me if there's a better way of handling this. I'm pretty new to scripting and I'd appreciate any feedback given. Thanks.
When a player is holding a tool it will always be in their actual player so all you need to do is set a variable for their humanoid. You can get rid of the first script all together and do this in the script inside the handle of your tool:
local tool = script.Parent.Parent tool.Activated:connect(function() name = tool.Parent local player = game.Players:FindFirstChild(name) local char = game.Workspace:FindFirstChild(name) local Torso = char:FindFirstChild("Torso") --Now you have the tool holders torso. end) function onTouch(hit) if hit.Parent:FindFirstChild("Humanoid") then if hit.Parent:FindFirstChild("Humanoid") == char.Humanoid then return end hit.Parent:FindFirstChild("Humanoid").Health = hit.Parent:FindFirstChild("Humanoid").Health - 10 else return end end part.Touched:connect(onTouch)