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

How to fix "nil values" without complicating everything?

I have this code for a basic obby, but the second line errors out. Here's my code:

local spawnNum = tonumber(script.Parent.Name)
local prevSp = spawnNum - 1

script.Parent.Touched:connect(function(touch)
	if touch.Parent:FindFirstChild("Humanoid") then
		local plr = game.Players:FindFirstChild(touch.Parent.Name)
		if plr:WaitForChild("leaderstats").Stage.Value == prevSp then
			plr:WaitForChild("leaderstats").Stage.Value = spawnNum
		else
			touch.Parent.Humanoid.Health = 0
		end
	end
end)

Errors out as: "attempt to perform arithmetic on local 'spawnNum' (a nil value)"

1 comment

0

Yes, my spawns are numbered.

1 answer

###Naming objects numbers is a bad idea, names are strings. In your SpawnLocation objects, insert an IntValue named Stage.

local nextStage = script.Parent.Stage 
-- IntValue named stage. Assigning the stage like this will make your life easier.
local Players = game:GetService("Players")

script.Parent.Touched:Connect(function(part)
    -- Switch to :Connect, :connect is deprecated 
    local plr = Players:GetPlayerFromCharacter(part.Parent)
    
    if plr then
        if plr.leaderstats.Stage.Value == nextStage.Value - 1 then 
            plr.leaderstats.Stage.Value = nextStage.Value
        end
    end
end)

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