While loops problem

for some reason even when the value is hoigher it will still get money away from the player and the part will not destroy for some weird reason.

local buyButton = script.Parent
local playerTouching = false
local cashGiven = script.Parent.CashGiven.Value
local cashNeeded = script.Parent.CashNeeded.Value

local function onPartTouched(otherPart)
	if otherPart.Parent:FindFirstChildOfClass("Humanoid") then
		playerTouching = true
	end
end

local function onPartTouchEnded(otherPart)
	if otherPart.Parent:FindFirstChildOfClass("Humanoid") then
		playerTouching = false
	end
end

buyButton.Touched:Connect(onPartTouched)
buyButton.TouchEnded:Connect(onPartTouchEnded)

script.Parent.Touched:Connect(function(hit)
	print("lol")
	local player = game:GetService("Players"):GetPlayerFromCharacter(hit.Parent)
	if player then
		while true do
			if playerTouching then
				if cashGiven < cashNeeded then
					player.leaderstats.Cash.Value -= 1
					script.Parent.CashGiven.Value += 1
				elseif cashGiven >= cashNeeded then
					script.Parent:Destroy()
					game.Workspace.Part.Transparency = 1
					break
				end
			end
			wait(0.2)
		end
	end
end)
print("aa")

Try not destroying the part and see if that makes a difference?

1 Like

You’re defining these variables at the start of the script outside of the loop, so they will never change. Move them inside of the while loop so they will update every time the loop runs.

1 Like