Code Issues Updating Text Labels for Nearby Customers Team

"Hello! I need a hand with my update of orderTextInfo. Currently, I’m managing it with a while true do loop, and it’s causing some trouble because I can’t properly press the button (the print statement doesn’t execute). How could I solve this issue, or what alternative fix could I implement to achieve the expected outcome of my functions?

Localscript:

local orderTextInfo = playerGui:WaitForChild("Order_Delivery").orderTextInfo

-- Function to check nearby customer
local function checkNearbyCustomer()
	local maxDistance = 15
	local player = game.Players.LocalPlayer
	local nearbyCustomer = ""

	for _, otherPlayer in ipairs(game.Players:GetPlayers()) do
		if otherPlayer ~= player and otherPlayer.Team.Name == "Customer" then
			local distance = (otherPlayer.Character.HumanoidRootPart.Position - player.Character.HumanoidRootPart.Position).magnitude
			if distance <= maxDistance then
				nearbyCustomer = otherPlayer.Name
				break
			end
		end
	end

	return nearbyCustomer
end

-- Function to update the order text based on nearby customer
local function updateOrderText()
	local nearbyCustomer = checkNearbyCustomer()
	if nearbyCustomer == "" then
		orderTextInfo.Text = "You are holding the Order of ... in your hands. Place the Tray/Plate on a green spot on the tables."
	else
		orderTextInfo.Text = "You are holding the Order of " .. nearbyCustomer .. " in your hands. Place the Tray/Plate on a green spot on the tables."
	end
end

local function updateOrderPeriodically()
	while true do
		updateOrderText()
		wait(1)
	end
end

-- Call the function to start updating the order text
updateOrderPeriodically()

-- Connect the MouseButton1Click event for the deliveryOrderButton
deliveryOrderButton.MouseButton1Click:Connect(function()
	print("Delivery order button pressed")
end)
1 Like

Put ‘updateOrderPeriodically()’ at the end of the script, it starts the loop before the MouseButton1Click connects thats why its not printing anything

2 Likes

Oh! Thank you very much, this worked perfectly. :smiley:

1 Like

what you can also do is this:

local function updateOrderPeriodically()
spawn(function()
while true do
		updateOrderText()
		wait(1)
	end
end)
end

“spawn function” will make it a co-routine for the compiler and will skip over it while still running it, you will probably find it very useful!

3 Likes

Thank you very much for your comment, it is very helpful! I will start using coroutines more often

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.