Code issues - Trying to destroy cloned templated

Hello! I’m trying to remove the cloned template in my order, but I’m encountering the following error shown below. Any ideas on how to fix it or what I might be doing wrong? :pray:

  11:58:24.782  Players.Player1.PlayerGui.Order_Delivery.deliveryOrderButton.deliveryButtonScript:13: attempt to index nil with 'WaitForChild'  -  Client - deliveryButtonScript:13

Project Organization:

server-side script:

local clonedTemplateEvent = game:GetService("ReplicatedStorage").orderTemplate:WaitForChild("clonedTemplateEvent")

-- Declare and initialize the orders table on the server side
local ordersTable = {}

clonedTemplateEvent.OnServerEvent:Connect(function(player, username, item1, item2, totalPrice)
	local frameTemplate = game:GetService("ReplicatedStorage").orderTemplate.Template
	local textLabelTemplate = frameTemplate.TextLabel

	-- Format the text for the textLabel
	local formattedText

	if item1 and item2 and item2 ~= "" then
		formattedText = "Order by " .. username .. ": " .. item1 .. " and " .. item2 .. ". Your earnings: $" .. totalPrice .. " CB"
	elseif item1 then
		formattedText = "Order by " .. username .. ": " .. item1 .. ". Your earnings: $" .. totalPrice .. " CB"
	else
		warn("No items provided for the order.")
		return
	end

	-- Loop through all players
	for _, plr in ipairs(game.Players:GetPlayers()) do
		if plr.Team and plr.Team.Name == "Chef" then
			-- Clone the frameTemplate into the ScrollingFrame
			local OrdersList_UI = plr:WaitForChild("PlayerGui"):FindFirstChild("OrdersList_UI")
			OrdersList_UI.Enabled = true

			local clonedFrame = frameTemplate:Clone()
			clonedFrame.Parent = OrdersList_UI.Background.ScrollingFrame

			-- Update the textLabel with formatted text
			clonedFrame.TextLabel.Text = formattedText

			-- Debugging: Print the content of textLabel to the console
			print("textLabel content:", clonedFrame.TextLabel.Text)
			
			-- Store the formatted text in the orderData for easy reference
			local orderData = {
				username = username,
				item1 = item1 or "",
				item2 = item2 or "",
				totalprice = totalPrice,
				formattedText = formattedText
			}
			
			table.insert(ordersTable, orderData)
			
		else
			warn("Player is not in Chef Team.")
		end
	end
end)

localsript:

local orderUpdateEvent = game:GetService("ReplicatedStorage").remoteEvents:WaitForChild("OrderUpdateEvent")

local orders = {}

-- Listen to the remote event to receive order update notifications
orderUpdateEvent.OnClientEvent:Connect(function(orderData)
	-- Update the client's UI with the new order data
	table.insert(orders, orderData)  -- Add the order to the local orders table
end)

-- Function to remove the delivered order from the orders table and UI
local function removeOrderAndUI(player, orderToRemove, index)
	local playerGui = player:WaitForChild("PlayerGui")
	local OrdersList_UI = playerGui:WaitForChild("OrdersList_UI")
	local scrollingFrame = OrdersList_UI.Background:WaitForChild("ScrollingFrame")
	local templateClone = scrollingFrame:WaitForChild("Template")

	-- Find and remove the template clone associated with the order from the UI
	for _, frame in ipairs(scrollingFrame:GetChildren()) do
		if frame.Name == "Template" and frame.TextLabel.Text == orderToRemove.formattedText then
			frame:Destroy()
			break
		end
	end

	-- Remove the delivered order from the orders table
	table.remove(orders, index)

	-- Print a message indicating successful removal
	print("Order successfully removed from orders table and UI. Index:", index)
end

-- Function to check nearby customer
local function checkNearbyCustomer()
	-- Check if there is a customer nearby and return their username if found
	local maxDistance = 15 -- Maximum distance to consider a player as nearby (adjust as needed)
	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 character = otherPlayer.Character
			if character and character:FindFirstChild("HumanoidRootPart") then
				local distance = (character.HumanoidRootPart.Position - player.Character.HumanoidRootPart.Position).magnitude
				if distance <= maxDistance then
					nearbyCustomer = otherPlayer.Name -- Set the nearby customer username
					break
				end
			end
		end
	end

	return nearbyCustomer
end

-- Function to check if the order exists in the orders table
local function checkOrderExists(username)
	-- Check if an order exists for a given username
	print("Checking if order exists for username:", username)
	for _, order in pairs(orders) do
		if order.username == username then
			print("Order found for username:", username)
			return true -- Order found
		end
	end
	print("Order not found for username:", username)
	return false -- Order not found
end

local deliverOrderFunction = game:GetService("ReplicatedStorage").remoteFunctions.deliverOrderFunction
local orderButton = script.Parent

orderButton.MouseButton1Click:Connect(function(player)  
	print("Delivery order button pressed")

	print(orders)

	-- Obtain the name of the nearby user
	local nearbyCustomer = checkNearbyCustomer()
	if nearbyCustomer == "" then
		print("No nearby customer found.")
		return
	end

	-- Check if there is an order for the nearby user
	local orderExistsForCustomer = checkOrderExists(nearbyCustomer)

	if orderExistsForCustomer then
		-- Get the order for the nearby user
		local orderData = nil
		local index = nil
		for i, order in ipairs(orders) do
			if order.username == nearbyCustomer then
				orderData = order
				index = i -- Store the index
				break
			end
		end

		if orderData then
			-- Print the order data before processing
			print("Order data before delivery:")
			for key, value in pairs(orderData) do
				print(key, value)
			end

			-- Check if orderData is valid before invoking deliverOrderFunction
			if not orderData.username or not orderData.item1 or not orderData.item2 or not orderData.totalprice then
				warn("Invalid order data")
				return
			end

			-- Call deliverOrderFunction with orderData and index
			print("Calling deliverOrderFunction with orderData and index:", orderData, index)
			if orderData and index then
				-- Get the RemoteFunction for delivering orders from the client
				local success, errorMessage = deliverOrderFunction:InvokeServer(orderData)
				if success then
					print("Order delivery successful.")

					-- Update any UI or data related to the removed order here
					local OrderReceivedByCustomer_UI = game.Players.LocalPlayer.PlayerGui:WaitForChild("OrderReceivedByCustomer_UI")
					OrderReceivedByCustomer_UI.Enabled = true
					OrderReceivedByCustomer_UI.ReceivedByCustomer_TextLabel.Text = "Order Received by ".. nearbyCustomer ..". + $".. orderData.totalprice .." CB"

					wait(3)
					OrderReceivedByCustomer_UI.Enabled = false
					wait(.2)
					-- Remove the delivered order from orderData
					orderData = nil

					-- Remove the delivered order from orders table
					table.remove(orders, index)
					removeOrderAndUI(orderData, index)

					-- Print a message indicating successful removal
					print("Order successfully removed from orders table. Index:", index)
					print(orderData)
				else
					print("Failed to deliver order:", errorMessage)
				end
			else
				warn("Order data or index is missing or nil")
			end
		else
			print("Failed to find order data for nearby customer:", nearbyCustomer)
		end
	else
		print("No order found for nearby customer:", nearbyCustomer)
	end
end)

You try to use removeOrderAndUI while also having an extra variable defined up here:

Since it’s a LocalScript, I’d try using game.Players.LocalPlayer

1 Like

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