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

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

Asked by 5 years ago

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

Log in to vote
1
Answered by
Pojoto 329 Moderation Voter
5 years ago

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)

0
Thanks, Pojoto, I just tried this and it works now. It use to be a bit more simple when I last scripted. Valuetainment 7 — 5y
0
You're welcome! Yeah, some things have changed... but they're for the better :) Pojoto 329 — 5y
Ad

Answer this question