Detect if a part is in another part

What I want to achieve is a system where I can drop for example 4 bananas and 2 watermelons inside an invisible part, and I can then use a function to count and return/print each part type and number individually.

Output e.g
4 bananas
2 watermelons

For the part type, I have an attribute in each part containing a string.

But well, I don’t actually know how I could do this. ( I don’t know if this topic has been covered, I just can’t find it )

Even if you know only how to detect if a part is inside another part, that would help!

If you know how to achieve this, please give me feedback
Thanks!

1 Like

You can use :GetTouchingParts()

part = -- put your object here
print(part:GetTouchingParts())

https://developer.roblox.com/en-us/api-reference/function/BasePart/GetTouchingParts

Then you can do something like:

Object = -- put your object here
TouchingParts = Object:GetTouchingParts()
total = {}

for _, part in ipairs(TouchingParts) do
  if total[part.Name] == nil then
    total[part.Name] = 1
  else
    total[part.Name] += 1
  end
end

print(total)
1 Like
for i,v in pairs(game.workspace:GetDescendants()) do
      if v.Parent:IsA("Basepart") then
             v.Parent.Transparency = 1
      end
end

if your talking about parents then this will work.

Took the idea, heres what I wrote.

local function CheckFruit()
	print("Started")
	local Area = workspace.Area
	local TouchingParts = Area:GetTouchingParts()
	
	for i,v in pairs(TouchingParts) do
		print(i)
		print(v)
	end
	print("Ended")
end

wait(15)

CheckFruit()

Output was just:

  • Started
  • Ended

I put the player in the part, and some of the fruit parts. So, its like it’s not detecting any parts. Do you know the issue?
Thanks!

Did you make sure your objects have CanCollide on? If you want it off, use this method to detect parts with CanCollide off.

Can collide is on when the player drops the part.
I also put the player inside the part. So, I know there is A part with CanCollide on

Does your Area part also have CanCollide off? You’ll have to do

local Connection = Area.Touched:Connect(function() end)
local TouchingParts = Area:GetTouchingParts()
Connection:Disconnect()
8 Likes

The area has can collide off, yeah
Oh, and that fixed it! Code now is

local Area = workspace.Area

local Connection = Area.Touched:Connect(function() end)

local function CheckFruit()
	local Connection = Area.Touched:Connect(function() end)
	local TouchingParts = Area:GetTouchingParts()
	for i,v in pairs(TouchingParts) do
		print(i)
		print(v)
	end
	Connection:Disconnect()
end

wait(10)

CheckFruit()

I’m going to integrate fruit owner detection, and things like that myself. Thanks for the help though!

2 Likes