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

This script works sometimes, and other times doesn't?

This script only works sometimes.

script.Parent.Touched:connect(function(hit)
	if not hit.Parent then return end
	
    local h = hit.Parent:FindFirstChild("Humanoid")

    if not h then return end

    h.WalkSpeed = 16 * 2

-----------------------------------------------------------------------------
	hit.Parent.Shirt.ShirtTemplate = "http://www.roblox.com/asset/?id=11404364"
	hit.Parent.Pants.PantsTemplate = "http://www.roblox.com/asset/?id=253433738"
-----------------------------------------------------------------------------
end)

4 comments

0

If you think about it, the second line is redundant. If "hit" can touch the part, then "hit" must have a parent, and that parent could be workspace, a model, etc.

0

Also, do you get an error in the output when it doesn't work?

0

hit.Parent CAN be nil, that check is NOT redundant.

0

How could hit.Parent possibly be nil? In order for parts to touch each other, it's at least assumed they're descendants of workspace.

1 answer

✓ Accepted answer

You don't really have to use all of these returns and such. You really don't need to check if the hit part has a parent either. Instead, lets just start our touch event first.

script.Parent.Touched:connect(function(hit)
	-- ...
end)

Now, we should use a Debounce because lets not spam this script's activation.

debounce = false -- You can change the variable to anything! (I use db)

script.Parent.Touched:connect(function(hit)
	if debounce == false then db = true --Instead of two lines, this shrinks the script, doing the same
		-- ...
	end
end)

Now we will check if an actual player touched it.

debounce = false -- You can change the variable to anything! (I use db)

script.Parent.Touched:connect(function(hit)
	if debounce == false then db = true --Instead of two lines, this shrinks the script, doing the same
		if hit.Parent:FindFirstChild("Humanoid") then
		-- ...
		end
	end
end)

Now, lets just add all of your code into this script.

debounce = false -- You can change the variable to anything! (I use db)

script.Parent.Touched:connect(function(hit)
	if debounce == false then db = true --Instead of two lines, this shrinks the script, doing the same
		local h = hit.Parent:FindFirstChild("Humanoid")
		if h then
			h.WalkSpeed = 16 * 2
			hit.Parent.Shirt.ShirtTemplate = "http://www.roblox.com/asset/?id=11404364"
			hit.Parent.Pants.PantsTemplate = "http://www.roblox.com/asset/?id=253433738"
		end
	end
	wait(1) -- This script will work again in 1 second
	db = false
end)

Above is the finished script.

  • If the player doesn't have a Shirt/Pants on, this will not work!

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