Sometimes my script works, sometimes it doesn't [SOLVED]

So sometimes when I interact with the prompt it gives me the error;
“Attempt to index nil with GetChildren”

And other times, it just works! I literally don’t notice any pattern. I’m really unsure what’s the problem.

So how can I prevent this from happening?

Here is my script; I apologize for it being so long.

game.Players.PlayerAdded:Connect(function(player)	
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Events = ReplicatedStorage.Events
	local text = "string"
	local inv =	player:FindFirstChild("Inventory")
	
	local function randomText()
		local textChoosen = math.random(1,3)

		if textChoosen == 1 then
			text = "you're not holding anything.."
		elseif textChoosen == 2 then
			text = "you need something?"
		elseif textChoosen == 3 then
			text = "can i help you?"
		end
end

local function checkForItem(player)
			for _,v in pairs(inv:GetChildren()) do -- here is where the problem is i think
				if v:IsA("Part") then
					print("Player has a tool! Detecting if it's purchased or not!")
					if v.Purchased.Value == false then
						print("Player has unpurchased item!")
						if v.Cost.Value <= player.leaderstats.Cash.Value then
							print("Player bought an item!")

							local rng = math.random(1,2)

							if rng == 1 then
								text = "thanks"
							else
								text = "anything else?"
							end
							player.leaderstats.Cash.Value -= v.Cost.Value
							v.Purchased.Value = true
						else
							print("Player brought already purchased item to shop!")

							local rng = math.random(1,2)

							if rng == 1 then
								text = "come back with money..."
							else
								text = "too poor..sry"
							end
							end
						end
					end
			end
	end
	
	script.Parent.Interaction.Triggered:Connect(function()
		script.Parent.Interaction.Enabled = false
			randomText()
			checkForItem(player)
		Events.Talking:FireClient(player,"Cashier",text,Color3.new(0.458824, 0.458824, 0.458824))
		wait(3)
		script.Parent.Interaction.Enabled = true
	end)
	end)
3 Likes

Try :WaitForChild rather than :FindFirstChild when you assign the inv variable.

4 Likes

That works! Thank you so much!

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