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

why is the .Touched event not working in roblox studio?

I started from the very basics in scripting again, and this simple touched event doesn't work. The part turns bright red as soon as I test the game, before being able to touch it.

script.Parent.Touched:connect(function()
	script.Parent.BrickColor = BrickColor.new("Bright red")
end)

1 answer

✓ Accepted answer

The problem here is that the Touched event is being called when it touches anything. So when the game started it was probably already touching something (maybe the baseplate) which made it turn red.

To fix this we need to check if the part that touched it is a player, not another part. The Touched event has this built in variable that tells you what part has touched it. We can use this to check if the part is a player. (I named the variable otherPart, you can name it whatever)

script.Parent.Touched:connect(function(otherPart)
	local humanoid = otherPart.Parent:FindFirstChild("Humanoid")
	if humanoid then
		script.Parent.BrickColor = BrickColor.new("Bright red")
	end	
end)

So inside the block we have made a variable called humanoid. This tries to find an object inside the part that touched it called "Humanoid". If it can't find it then it will become nill and we know it is not a player.

In the next line we typed, if humanoid then. This basically says, "If the humanoid variable exists then..."

Then we execute our code.

script.Parent.BrickColor = BrickColor.new("Bright red")

This above code will only run if: A) The part is touched and B) The part that touched it has an object called "Humanoid" inside it. (All players have this inside of them)

2 comments

0

Thanks, Pojoto, I just tried this and it works now. It use to be a bit more simple when I last scripted.

0

You're welcome! Yeah, some things have changed... but they're for the better :)

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