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

i'm getting this error "attempt to index a nil value" how do i stop it?

Asked by 6 years ago
Edited 6 years ago

i'm making a claim for a tycoon game and i'm getting this error for the claim. the script is still doing what i want it to just it's still giving the error

"Workspace.Claim.GateControl:8: attempt to index a nil value"

this is the script that i have

01local BValue = script.Parent.BValue
02local Owner = script.Parent.Owner
03local BillBoard = script.Parent.BillBoard.SurfaceGui.TextLabel
04 
05script.Parent.Head.Touched:connect(function(hit)
06    local player = game.Players:GetPlayerFromCharacter(hit.Parent)
07    local playerName = hit.Parent.Name
08    local Owning = game.Players:FindFirstChild(playerName).Owning
09        if player ~= nil then
10            if hit.Parent:FindFirstChild("Humanoid") then
11                if hit.Parent.Humanoid.Health > 0 then
12                    if BValue.Value == false then
13                        if Owning.Value == false then
14                            Owner.Value = playerName
15                                BillBoard.Text = playerName
View all 25 lines...
0
Mother of god. User#19524 175 — 6y
0
So much nesting.  You can also use "and' and "elseif" op. ABK2017 406 — 6y
0
and ":Connect" ABK2017 406 — 6y

1 answer

Log in to vote
0
Answered by 6 years ago

While your issue is specifically with line 8, there's a lot of unneeded code in your script that could be cleaned up. Your issue is that you're checking if the player exists after you're checking for player.Owning, which means that if anything besides a player touches the head then it will error. This specific issue can be fixed by swapping lines 8 and 9, but a bunch of the code you've written is unneeded.

Another issue with your code (your script will still work if you ignore this) is that you're defining a variable and then basically redefining it two lines later. You're creating a variable for player, but then you're checking game.Players for something of the player's name (which will return the player if the player exists). This is like writing x.Parent:FindFirstChild(x.Name), it's pointless and you already have the variable you need (in the example, x). Since you already have a variable for the player, you can shorten line 8 (line 9 with fix) to local Owning = player.Owning. One more thing with your code that doesn't matter as much: if player ~= nil is the same thing as writing if player, no need to compare to nil.

0
thanks i mooved line 8 to line 12 Nooberton_1 9 — 6y
Ad

Answer this question