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

What is the easiest way to find the player in a PVP setting?

Asked by 6 years ago

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.

1 answer

Log in to vote
0
Answered by 6 years ago
Edited 6 years ago

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)
Ad

Answer this question