Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

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

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

✓ Accepted answer

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!

This discussion is preserved as it was. New answers, comments, and votes are closed.