My while true loop does not work

Greetings,
I am making a script to enable and disable a crosshair. However the while true loop does not work. Here is the script (simplified to understand the issue)

local noCross = false

local UIS = game:GetService("UserInputService")

UIS.InputBegan:Connect(function(i, v)
	if i.KeyCode == Enum.KeyCode.F then
		noCross = true
		print("Disabling Crosshair")
		print(noCross)
	end
end)

UIS.InputBegan:Connect(function(i, v)
	if i.KeyCode == Enum.KeyCode.H then
		noCross = false
		print("Enabling Crosshair")
		print(noCross)
	end
end)
 
while noCross do 
	wait()
	print("Crosshair Enabled")
end

Everything works except for the while noCroos do loop. Do you know what’s the problem?
Thanks,
-Yolo

1 Like

The code is all being read at the same time, so if you pass a while loop when noCross == false there’s no way to access the while loop again without using a wait or function.

1 Like

hmm, so what should I do about it?

Try firing a function at the end after each event within the if statement. This will ensure that a loop will begin. Although crosshairs shouldn’t employ a while true loop at all, it is only by replacing the mouse icon with another image.

1 Like

So what you are saying is to do this?

local function functionName()

end
while noCross do 
	wait()
	print("Crosshair Enabled")
        functionName()
end

P.S. The original script is from a GTA RP server that I am making, hence the disable crosshair command needs to be in a loop since the command is HideHudComponentThisFrame(14)

That’s not exactly what I implied. I told you “end after each event”, not in the loop.

local function stepFunction()
    while noCross do
        -- code here
    end
end

UIS.InputBegan:Connect(function(i, v)
	if i.KeyCode == Enum.KeyCode.F then
		noCross = true
		print("Disabling Crosshair")
		stepFunction()
	end
end)

UIS.InputBegan:Connect(function(i, v)
	if i.KeyCode == Enum.KeyCode.H then
		noCross = false
		print("Enabling Crosshair")
		stepFunction()
	end
end)

Although the code works, it shouldn’t look like that, do this instead:

local function stepFunction()
    while noCross do
        -- code here
    end
end

UIS.InputBegan:Connect(function(i, v)
	if i.KeyCode == Enum.KeyCode.F then
		noCross = true
		print("Disabling Crosshair")
		stepFunction()
	elseif i.KeyCode == Enum.KeyCode.H then
		noCross = false
		print("Enabling Crosshair")
	end
end)

You can also move the entire while loop into the scope over the stepFunction() instead.

1 Like

Thank you for the epic solution of yours. This will help my GTAV RP server. Appreciate it.