Hello.
I am working on a script where touching the “Connection” part initiates a connection and touching the “Disconnect” part disconnects it.
The connection itself works fine, but when I touch the “Disconnect” part, it does a :Disconnect() and it disconnects correctly, but I can’t reconnect it again.
This is for temporary local control of a particular part.
How can I make it possible to connect and disconnect as many times as I want?
local a
a = Part.Touched:Connect(function(hit)
if hit.Name == "Connection" then
--Arbitrary operation
end
if hit.Name == "Disconnect" then
a:Disconnect()
end
end)
Is that after disconnection?
My script does not allow me to run the function again after disconnecting. (Nothing happens when I touch it.)
I want to reset the connection to the target part once.
I am making a game about trains, and I am trying to make a melody play when the train stops at a station and certain keys are pressed.
I want the melody to play only while the player is at that station, so once the player leaves the station, I want to disconnect the player from the station so that he/she cannot control it from afar.
Once an event gets disconnected, it is destroyed, there is no such function to enable it.
So instead you can make a state variable which determines whether the event should be ran, just like this:
local state = true
Part.Touched:Connect(function(hit)
if hit.Name == "Connection" then
state = true
end
if hit.Name == "Disconnect" then
state = false
return
end
--adding the if statement here as i assume whether you want to execute the main code in this scope
if state == false then return end
--Code here
end)
While there are other methods to achieve this solution depending on what you are trying to achieve, this is what i’ve found to be more efficient based on how i’ve looked on your problem.
That’s what I mean. There is a “Connection” part in the middle of the station and a “Disconnect” part a little further away from the station.
If a train touches the “Disconnect” part, it will no longer communicate with that station.
You could create another touched event every time Conncetion is touched but it would be better if you switched over to using a debounce rather than disconnecting and reconnecting a connection.
local isPlayingMelody = false
a = Part.Touched:Connect(function(hit)
if hit.Name == "Connection" and not isPlayingMelody then
--Run code to play melody
end
if hit.Name == "Disconnect"and isPlayingMelody then
isPlayingMelody = false
--Run code to stop melody
end
end)
Thanks for the advice.
I have tried it, but it seems that when I touch Disconnect in the first place, it does not work at all.
I have also tried hit = nil, but it does not work.