Hi everyone.
I am working on a system where cars with no one sitting in them will be destroyed after a certain amount of time.
I’m currently struggling with a script that starts a 30-second countdown when no one is sitting in VehicleSeat, and when someone sits in the car, it stops the countdown and returns the number to 30.
local timer = script.Parent.Timer
local sitting = script.Parent.Parent.Sitting
sitting:GetPropertyChangedSignal("Value"):Connect(function()
if sitting.Value == false then --座っている
for i = 30,0,-1 do
timer.Text = i
wait(1)
end
else
timer.Text = "30"
end
end)
This script does not start counting down until you sit down and then leave the seat (it stays at 30 right after it starts), and each time you sit down again, a new countdown starts.
I have also tried break, but it does not destroy well.
Thanks for reading.
local timer = script.Parent.Timer
local sitting = script.Parent.Parent.Sitting
sitting:GetPropertyChangedSignal("Value"):Connect(function()
if sitting.Value == false then --座っている
for i = 30,0,-1 do
timer.Text = tostring(I)
wait(1)
end
else
timer.Text = "30"
end
end)
This may occur due to multiple loops running simultaneously(every time the property changes a new loop starts). Instead another loop should be responsible for the timer and the BoolValue .Changed should only be used for changing the value that handles the loop.
local timer = script.Parent.Timer
local sitting = script.Parent.Parent.Sitting
--change this to true, if you want to avoid the car being destroyed after spawning
local active = false
sitting.Changed:Connect(function(value)
active = value
end)
--a single loop running at once
while task.wait(1) do
if not active then
timer.Text = tonumber(timer.Text)-1
else
timer.Text = "30"
end
end
@Milcheks
Thank you for your prompt response.
I just found out that break can only be used for infinite loops.
@Winbloo
I tried the script you provided, but it either returns nil or starts the countdown regardless of the seating position.
But thanks for your advice!
@NyrionDev
It worked perfectly!
Thanks for all the great advice!