I am making a script so when you die, it sets your spawn to the stage you are at. This is my code:

delay(2,workspace.ChildAdded:connect(function(obj) --the delay makes it wait 2 seconds. it's for test purposes only, will be removed later
	local plr = game.Players:GetPlayerFromCharacter(obj)
	if plr ~= nil then
		local ls = plr.leaderstats
		local val = ls.Stage.Value
		local spawnr = workspace.Spawns:FindFirstChild(val)
		if obj:FindFirstChild("Torso") ~= nil then
			obj.Torso.CFrame = spawnr.CFrame + Vector3.new(0,3,0)
		elseif obj:FindFirstChild("UpperTorso") ~= nil then
			obj.UpperTorso.CFrame = spawnr.CFrame + Vector3.new(0,3,0)
		end
	end
end))

Everything is working fine, except of this one error:

attempt to index local 'spawnr' (a nil value)

It doesn't make sense, as I made it a variable, shown here

local spawnr = workspace.Spawns:FindFirstChild(val)

What is my problem here?

2 comments

0

FindFirstChild will return nil if the child it not found

0

Yea you'll need to make sure it's not nil. You could switch to :WaitForChild(), but :shrug: