How to check when a part enters and leaves another part?

You can write your topic however you want, but you need to answer these questions:

  1. What do you want to achieve? Keep it simple and clear!
    I want to be able to make a part red if it goes inside of another part and green when it leaves that part/isn’t in a part

  2. What is the issue? Include screenshots / videos if possible!
    I don’t know how to do it.

  3. What solutions have you tried so far? Did you look for solutions on the Developer Hub?
    I have tried YT and Devforum

1 Like

GetPartsInPart() returns an array with every part inside of another part

local hitboxPart = game.Workspace.hitboxPart -- the hitbox
local otherPart = game.Workspace.otherPart -- the part we are looking for

while task.wait() do
  local touchingParts = workspace:GetPartsInPart(hitboxPart) -- get the array of touching parts
  local partFound = false -- variable to keep track of if the part is touching the hitbox parts
  for i,v in pairs(touchingParts) do -- loop through the parts touching the hitbox part
    if v == otherPart then -- if the current part is the part we are searching for
      partFound = true -- we know that the part has been found now
      break -- stop searching
  end
  
  if partFound == true then
    print("The other part is touching the hitbox part")
    --you could make the part green here
  else
    print("The other part is not touching the hitbox part")
    --you could make the part the normal color here if its not touching
  end
end
1 Like

If the touch is physics-based(meaning this isn’t an interaction between 2 anchored parts through a script) use Touched and TouchEnded:

Part.Touched:Connect(function(hit)
	print(Part.Name, "entered", hit.Name) 
end)
Part.TouchEnded:Connect(function(hit)
	print(Part.Name, "left", hit.Name)
end)

My one part is anchored and the other one isnt, but im also using a local script. So this doesnt work for me

I think it works if you set Part as the unanchored part. If not then you may want to use other methods like GetPartsInPart(shown above) that also work for non-physics-based movements(for example anchored parts).

if you talk about player so here:

local part = your part
local touching = false
while wait(0.2) do
   local parts = part:GetTouchingParts()
   for index, part in pairs(parts) do
      if part.Parent:FindFirstChild("Humanoid") and game.Players:GetPlayerFromCharacter(part.Parent) then
         touching = true
      end
   end
   if touching then
       -- code
   else
       -- code
   end
   touching = false
end

for just part here:

local part = your part
local touching = false
while wait(0.2) do
   local parts = part:GetTouchingParts()
   for index, part in pairs(parts) do
      touching = true
   end
   if touching then
       -- code
   else
       -- code
   end
   touching = false
end