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

Why is this not detecting the player's backpack? [RESOLVED, THANK YOU]

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!

2 answers

✓ Accepted answer

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)

3 comments

0

Try adding a Debounce.

2

@ TheContinentofEurope That's probably a good idea, but it's not the issue the person was having. They would've probably figured out they should use a debounce anyway, and if not, they could just post another question for that; they are very different issues after all.

0

Excellent explanation and answer. Great job!

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...

1 comment

0

Nope, that didn't work. It doesn't matter if you make a variable and store that information, it won't work. I know the problem but I don't know how to fix it - it's not getting the player from the character for some reason.

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