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

Why does this script result in an error when the SpawnLocation is touched by a player?

Asked by 7 years ago

Why does this script result in an error when the SpawnLocation is touched by a player? Output displayed "Humanoid is not a valid member of Workspace."

local debounce = false

script.Parent.Touched:connect(function(hit)
    if not debounce then
        debounce = true
        if hit.Parent.Humanoid.WalkSpeed >= 32 then
            hit.Parent.Humanoid.WalkSpeed = hit.Parent.Humanoid.WalkSpeed - 16
        end
        wait(1)
        debounce = false
    end
end)

I did find the solution to fix this problem, but is there a better way?

local debounce = false

script.Parent.Touched:connect(function(hit)
    if not debounce then
        debounce = true
        local player = game:GetService("Players"):GetPlayerFromCharacter(hit.Parent)
        if player then
            if player.RespawnLocation ~= script.Parent then
                player.RespawnLocation = script.Parent
            end
        end
        if hit.Parent.Name ~= "Workspace" then -- My solution
            if hit.Parent.Humanoid.WalkSpeed >= 32 then
                hit.Parent.Humanoid.WalkSpeed = hit.Parent.Humanoid.WalkSpeed - 16
            end
        end
        wait(1)
        debounce = false
    end
end)

Thanks!

1 answer

Log in to vote
0
Answered by
legosweat 334 Moderation Voter
7 years ago
Edited 7 years ago

I see you have found the solution, and yes there is a better way of doing this!

Saying this:


if hit.Parent.Name ~= "Workspace" then

is very inefficient, this is because the parent will not always be Workspace. For example, a part in a group, its parent would be the group and not the Workspace.

Essentially what we can do is check for a humanoid in the player, basically checking if the part that has touched it is a part of a player and not a random part.

So in conclusion make a variable using :FindFirstChild() to find the Humanoid, and then you can if the variable. If humanoid was not found, the if statement will error and not continue further, and that's kinda what we want.

Finalized Code:


local debounce = false script.Parent.Touched:connect(function(hit) if not debounce then debounce = true local checkifplayer = hit.Parent:FindFirstChild("Humanoid") if checkifplayer then local player = game:GetService("Players"):GetPlayerFromCharacter(hit.Parent) if player then if player.RespawnLocation ~= script.Parent then player.RespawnLocation = script.Parent end end wait(1) debounce = false end end end)

Also you might see I put the check before we start doing stuff with the player, that is to cut some slack for the script. If there was no player, the script would not function correctly.

Hope this helped!

Ad

Answer this question