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

Why is this resulting in a 'attempt to index local 'plyr' (a nil value)' error, but still working?

Asked by 5 years ago

I have a portal that only allows access past a certain Stage.Value and it works fine... once. Prior to this I didn't have the debounce which caused the message to fire way too many times when someone under the required level tried to access it. With the debounce it works as intended for both the message and the initial teleport but if I come back to the portal in the same session it does nothing.

This error pops up in the console after/during the initial teleport so I presume it is disabling the script in some way? attempt to index local 'plyr' (a nil value)

Or my code is just pure rubbish lol.

Any thoughts?

local place = CFrame.new(61.861, 310.247, 245.514) -- Where you want the player to go on touched
local debounce=true

script.Parent.Touched:Connect(function(part)
    if debounce == true then
       debounce = false
    local parent = part.Parent
    local plyr = game.Players:GetPlayerFromCharacter(parent)
    if (plyr.leaderstats.Stage.Value < 25) then
        local note = Instance.new("Message",game.Workspace)
        note.Text = "Requires Stage 25 to access"
        wait(2)
        note:Remove()
        debounce = true
    elseif (plyr.leaderstats.Stage.Value >= 25) then
        local plyrmod = plyr.Character.HumanoidRootPart
        plyrmod.CFrame = place
        debounce = true 
    end
    end
end)

1 answer

Log in to vote
0
Answered by 5 years ago

I believe this happens because you're not checking if the parent has a humanoid (which players do, in most cases).

A simple solution would be to use :FindFirstChildOfClass("Humanoid") to see if there is a humanoid in the parent, if there is, then toggle the debounce.

Example:

local debounce = true;
local Players = game:GetService("Players");

script.Parent.Touched:Connect( function (hit)
    if hit.Parent:FindFirstChildOfClass("Humanoid") then
        -- Is a player or NPC 
        debounce = false;
        local player = Players:GetPlayerFromCharacter(script.Parent);
        -- Continue 

        wait(2)
        debounce = true;

        else

        -- Not a player or NPC
    end
end)
0
That's something I really need to get used to doing! Thanks for explaining it in such user friendly terms :) GrumpyTheDaddy 17 — 5y
0
Would this explain why it would only fire once and then fail thereafter? GrumpyTheDaddy 17 — 5y
0
Finally had time to test this... and success, thank you so much!! GrumpyTheDaddy 17 — 5y
Ad

Answer this question