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

"attempt to index a nil value" problem eventhough everything looks correct?

So when you steal the tool from another play it should add one to steal value but doesnt. It doesnt even let u steal the ball?

local tool=script.Parent
local handle=tool:findFirstChild("Handle")
local lastPlayer = tool:FindFirstChild("LastPlayer")

handle.Touched:connect(function(hit)
	local person=hit.Parent
	if person:IsA("Hat") then
		if person.Parent==workspace then person:Destroy() end
	elseif person:findFirstChild("Humanoid") then
		local Player=game.Players:findFirstChild(person.Name)
		if Player then
			script.Disabled=true
			tool.Parent=workspace 
			wait() tool.Parent=person
			lastPlayer.Value = Player.Name
			person:WaitForChild("leaderstats").STL.Value = person:WaitForChild("leaderstats").STL.Value + 1
		end
		wait(2)
	end
	script.Disabled=false
end)



2 comments

0

"Hat" s are deprecated, use "Accessory"

0

there an error on line 16

1 answer

GENERAL PRACTICE

Use :WaitForChild() if you are going to change an existing part, since the child you are trying to find may not be loaded yet

Use the :GetPlayerFromCharacter() method of getting a character rather than FindFirstChild() This is needed since a part may be added to the Players Service with the same name as the player.

When giving a player a tool, add it to the player's backpack, where it then goes to the character, not directly giving it to the player

Add a debounce so that players cannot spam the activation of the touched event.

ISSUES

The hit.Parent is not both the player and the character. The leaderstats should be under the player, not the character.

If you disable the script while it is working, the remainder of the code cannot be run

connect is deprecated in favor of Connect

Use "FindFirstChild" instead of "findFirstChild"

REVISED SERVER SCRIPT

local tool = script.Parent
local handle = tool:WaitForChild("Handle")
local lastPlayer = tool:WaitForChild("LastPlayer")
local debounce = true

handle.Touched:Connect(function(hit)
	if debounce == false then return end
	debounce = false
	local character = hit.Parent
	if character:FindFirstChild("Humanoid") then
		local Player = game:GetService("Players"):GetPlayerFromCharacter(character)
		if Player then
			tool.Parent = Player:WaitForChild("Backpack")
			lastPlayer.Value = Player.Name
			local stl = Player:WaitForChild("leaderstats"):WaitForChild("STL")
			stl.Value = stl.Value + 1
		end
		wait(2)
	elseif character:IsA("Accessory") and character.Parent == workspace then
		character:Destroy()
	end
	debounce = true
end)

Also not sure why you need to remove the accessory if there is no player? But you should probably use this as a second event, rather than the first.

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