function ontouch(part) local h = part.Parent:findFirstChild("Humanoid") if h ~= nil then local plr = game.Players:GetPlayerFromCharacter(h) if plr ~= nil then game.Lighting.LinkedSword:Clone().Parent = plr.Backpack end end end script.Parent.Touched:connect(ontouch)
I suspect that the problem is in the local plr = game.Players:GetPlayerFromCharacter(h)
line, but I'm not sure what I have done wrong. Please help me through this and be sure to explain your answer to me so that I know what the problem is in the future. Thank you!
You were right about the problem being with local plr = game.Players:GetPlayerFromCharacter(h)
. The GetPlayerFromCharacter method should be used on character models, not humanoids; so instead, you should do this:
local plr = game.Players:GetPlayerFromCharacter(part.Parent)
You can also use h.Parent
instead of part.Parent
if you want, but it's a bit redundant to look for the Humanoid if you're just going to use the parent anyway. Instead, you can leave the whole check if there is a humanoid out, and just do:
function ontouch(part) local plr = game.Players:GetPlayerFromCharacter(part.Parent) if plr ~= nil then sword = game.Lighting.LinkedSword:Clone() sword.Parent = plr.Backpack end end script.Parent.Touched:connect(ontouch)
function ontouch(part) local h = part.Parent:findFirstChild("Humanoid") if h ~= nil then local plr = game.Players:GetPlayerFromCharacter(h) if plr ~= nil then sword = game.Lighting.LinkedSword:Clone() sword.Parent = plr.Backpack end end end script.Parent.Touched:connect(ontouch)
function getPlayer(Part) local Humanoid = Part.Parent:FindFirstChild('Humanoid') if (Humanoid ~= nil) then local Character = Humanoid.Parent if (Character ~= nil) then return game:GetService('Players'):GetPlayerFromCharacter(Character) end end end
Try this to get it, use parts do this code I posted to get the player, may or may not work...