Multiple E to Interacts

I am trying to create a kitchen system for my cafe using E to interact. Currently so far I have:

local Part = game.Workspace.WaterDispenser
local UserInputService = game:GetService("UserInputService")
local Player = game.Players.LocalPlayer.Character:WaitForChild("HumanoidRootPart")

UserInputService.InputBegan:Connect(function(KeyCode)
    if KeyCode.KeyCode == Enum.KeyCode.E then
        if (Part.Position - game:GetService("Workspace").CurrentCamera.CFrame.Position).magnitude < 7 then
            print("change player.character.cup to water")
        end
    end
end)

Part.BillboardGui.ImageButton.TouchTap:Connect(function()
    if (Part.Position - game:GetService("Workspace").CurrentCamera.CFrame.Position).magnitude < 7 then
        print("change player.character.cup to water")
	end 
end)

The issue is that if I have multiple (for example) syrup bottles next to each other and the player is holding out a cup, I don’t know how to make it precise so that whichever bottle is closest to the player the billboard gui will be visible. I’m trying to make it like bloxburg so that there’s only one billboard gui showing at a time. I’m using the touchtap function so that the system is also functioning for mobile users. The billboard gui is inside the clear part.

local UserInputService = game:GetService("UserInputService")
local Player = game.Players.LocalPlayer.Character:WaitForChild("HumanoidRootPart")

local function findClosestPart()
	local lastMag, chosenPart = math.huge, nil;
	for _, v in pairs(workspace.TouchParts:GetChildren()) do
	local newMag = (v.Position - workspace.CurrentCamera.CFrame.p).Magnitude
		if newMag  < lastMag then
		lastMag = newMag 
		chosenPart = v
		end
	end
	return chosenPart, lastMag
end

UserInputService.InputBegan:Connect(function(KeyCode)
    if KeyCode.KeyCode == Enum.KeyCode.E then
    	local closestPart, closestPartMagnitudeFromCamera = findClosestPart()
    	print(closestPart:GetFullName().." is the closest part")
        if closestPartMagnitudeFromCamera < 7 then
            print("change player.character.cup to water")
        end
    end
end)

-- set billboardgui max dist to 7 so they only show up when they are close enough
for _, v in pairs(workspace.TouchParts:GetChildren()) do
	v.BillboardGui.ImageButton.TouchTap:Connect(function()
		local closestPart, closestPartMagnitudeFromCamera = findClosestPart()
		print(closestPart:GetFullName().." is the closest part")
	    if closestPartMagnitudeFromCamera < 7 then
	        print("change player.character.cup to water")
		end 
	end)
end
1 Like

Thank you! So if I want to check if the closest part is a orange syrup then should do if closetPart.Name == "OrangeSyrup" then ?

yep :ok_hand:
30char30char30char

Thank you! Also what is workspace.TouchParts? I get an error when I run the code.

put all of the parts that have the GUI in them in one folder in workspace