Hello there! I’m trying to script a train when it’s moving forward all the time but if it hits a part, it will stop for a certain amount of time, I’ve created two server-sided scripts so I used a bindable event. It’s not working or printing an error in the output. Here are my scripts:
--In the part
local part = script.Parent
local debounce = false
part.Touched:Connect(function(hit)
if debounce == false then
debounce = true
if hit.Parent.Name == "Locomotive" then
game.ReplicatedStorage.StartStopTrain:Fire()
wait(10)
debounce = false
end
end
end)
--In the Drive seat in the train
local enabled = true
if enabled == true then
script.Parent.Throttle = 1
else
if enabled == false then
script.Parent.Throttle = 0
end
end
game.ReplicatedStorage.StartStopTrain.Event:Connect(function()
enabled = false
end)
It seems as if you never set the throttle after the event is fired. You’re doing so when the script initialized, but other than that your if statement never gets run again.
In this case, you’re simply just changing a bool value.
There are many adjustments you can make to make your code a little cleaner, but for this case, I’ll just show you my proposed solution.
To fix this, I’d try making your if statement a function, and calling it when the event is fired like so:
--In the Drive seat in the train
local enabled = true
function setThrottle()
if enabled == true then
script.Parent.Throttle = 1
else
if enabled == false then
script.Parent.Throttle = 0
end
end
end
setThrottle()
game.ReplicatedStorage.StartStopTrain.Event:Connect(function()
enabled = false
setThrottle()
end)
It only checks the enabled variable once when the script first starts, so you have to put it in the Event itself. But it’ll never set it to true anymore, so fire the event again after the train can move again, and your Event code in the drive seat should be like this
local enabled = true
game.ReplicatedStorage.StartStopTrain.Event:Connect(function()
enabled = not enabled
script.Parent.Throttle = enabled and 1 or 0
end)
So it’ll invert the value of enabled and set the Throttle depending on the value in the variable. The only other thing you gotta do is fire the event again when the train is allowed to move again
There are other ways you can write the code in the event, but this is simplest as we can just invert the value in enabled and then use a Tenary operator to do something if enabled is true or false,
script.Parent.Throttle = enabled and 1 or 0
is basically the same as
if enabled then
script.Parent.Throttle = 1
else
script.Parent.Throttle = 0
end