Don't understand how if statement for filtering touched parts works

Hi I just wanted someone to explain how the game knows to delete Yellow if it’s touching YellowPart, but to not delete lets just say red if it’s touching YellowPart using this code.

local Yellow = game.Workspace.Yellow
local YellowPart = game.Workspace.YellowPart

game.Workspace.Yellow.Touched:Connect(function(partTouching)
if YellowPart ==  partTouching then  
    YellowPart:Destroy()
end
 end)

Thanks.

1 Like

You have told it to do so. The == operator compares both of its operands and returns true if they are the same otherwise false. So it passes the conditional test and proceeds with destroying.

The argument in the parenthesis represents the instance that fired the event. In this case the event is Touched and the instance that fired the event is partTouching, so partTouching represents the part that touched Yellow.

Now, you’re saying that if YellowPart is the part that touched yellow, then destroy it.

Also, why would you do this:

If you’re never even going to use that variable.

I thought I had to make the variable so it knows what Yellow is, sorry I’m new to lua.

Ok, making variables for instances is basically a shortcut.

Instead of doing

game.Workspace.Yellow.Touched:Connect(function()

end)

You can do:

local blah = game.Workspace.Yellow

blah.Touched:Connect(function()

end)

Also, here are some great tutorials on functions and events.
Functions: Functions | Documentation - Roblox Creator Hub
Events: Events | Documentation - Roblox Creator Hub