Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How to fix "nil values" without complicating everything?

Asked by
Ap_inity 112
5 years ago

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)"

0
Yes, my spawns are numbered. Ap_inity 112 — 5y

1 answer

Log in to vote
0
Answered by 5 years ago
Edited 5 years ago

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)
Ad

Answer this question