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

How would I solve this problem about someone reseting?

Asked by 5 years ago

If someone resets while having a ForceField the code will get a error and not work. How would I go about solving this issue.

    local players = game.Players:GetChildren()
    for i, plr in ipairs(players) do
    local shieldCheck = plr.Character:FindFirstChildOfClass("ForceField")
    shieldCheck:Destroy()

Error I am getting: ServerScriptService.mainscript:58: attempt to index local 'shieldCheck' (a nil value)

1
Check if shieldCheck exists before attempting to call :Destroy() on it. FindFirstChildOfClass will return nil if it cannot find the class it was fed. CorruptScript 86 — 5y
0
Thanks! I knew it was something simple like that. dracefiery 4 — 5y

1 answer

Log in to vote
0
Answered by 5 years ago

Reiterating what was previously mentioned in the comments, your problem is that the script is told to destroy a ForceField that may or may not exist.

If you run that code and the player's character doesn't have a child of the ForceField class, the variable shieldCheck gets set to nil. You can't call :Destroy() on nil. It doesn't make sense.

Therefore you have to check if the ForceField exists before trying to destroy it. It's fairly simple. Appending what you posted already, it would look like this:

local players = game.Players:GetChildren()
for i, plr in ipairs(players) do
    local shieldCheck = plr.Character:FindFirstChildOfClass("ForceField")
    if shieldCheck then
        shieldCheck:Destroy()
    end
Ad

Answer this question