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

Why is the error "attempt to index a nil value" showing up?

Script's located inside a NPC's torso and meant to get replaced by any players that touches him/her. It says there's an error on line 3 when I clearly see none. I'd like to know why the error keeps popping up in the output. Script:

script.Parent.Touched:connect(function(P)
	if game.Players:FindFirstChild(P.Parent.Name) then
		P.Parent:Clone().Name = "Player"
game.Workspace:FindFirstChild("Player").PrimaryPart.Position = Vector3.new(CFrame.new(script.Parent.Position))
script:Clone().Parent = game.Workspace:FindFirstChild("Player").PrimaryPart
script.Parent.Parent:Destroy()
	end
	end)

1 answer

✓ Accepted answer

By default, character models have Archivable set to false. This means that they can't be cloned, resulting in it returning nil when you try to clone it, so all you should need to do is set Archivable to true before cloning.

As well as this, when you use FindFirstChild in workspace for a player, it will not necessarily be the model you have cloned if there is something else called player. Instead, a better practice would be to make a variable for the cloned character and edit it through that variable. For example:

local debounce = true
script.Parent.Touched:Connect(function(hit)
	if game.Players:GetPlayerFromCharacter(hit.Parent) and debounce then
		debounce = false
		hit.Parent.Archivable = true
		local clone = hit.Parent:Clone()
		clone.Name = "Player"
		clone.HumanoidRootPart.CFrame = script.Parent.CFrame
		clone.Parent = workspace
		script:Clone().Parent = clone.HumanoidRootPart
		wait(5)
		debounce = true
	end
end)

I've also added a debounce so you don't completely break your game.

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