Title
Main problem is that if i put a print inside the loop, it always prints true, even if the variable outside is set to false
I have basically tried everything at this point:
putting the loop inside task.spawn (as well as coroutine)
putting a if statement inside to break
local levent = game.ReplicatedStorage.lEvent
levent.Event:Connect(function(cameraenabled)
if cameraenabled then
while cameraenabled do
local Image = script.Parent
local a = 0.03
task.wait(a)
-- more code, doesent change "cameraenabled" variable
end
end
end)
sorry I’m not sure if I understand. do you mean that if you trigger the event with cameraenabled set to true and then you trigger the event again with cameraenabled set to false, the first loop still continues? or do you just mean that you fired the event with cameraenabled set to false and the script thinks its true
I did
Printing the variable right before the if (before the loop) prints it correctly, while printing it inside of the loop always prints “true”, even if I send a “false”
Each time an event is fired, its connected functions are executed in a separate thread. Firing the event with falsewill not affect previous function calls, but simply generate a new function call with a different context
You can set up an upvalue for the loop to use as its condition, that way changes to the upvalue from future function calls can affect previous ones:
local cameraEnabled = false
local function onSetCameraEnabled(enabled: boolean)
cameraEnabled = enabled
while cameraEnabled do
-- ...
end
end
setCameraEnabled.Event:Connect(onSetCameraEnabled)
(Please try to use concise variable names from hereon)