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)
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)