Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

script runs even after player no longer meets requirements?

Asked by 5 years ago
Edited 5 years ago

Hello, I am unknown why this program doesn't work like it is meant to. Basically it checks if a player is in the seat, then allows them to 'press e' (For debugging atm) and only lets them do that if they remain in the seat. However I noticed that it allows it to continue even after the player left the seat.

Anyone got a solution? Much thanks!

01local UserInputService = game:GetService("UserInputService")
02local Car = game.Workspace.Car
03local CarBase = Car.CarBase
04local CarMoving = Car.CarMoving
05local CarSeat = Car.Seat
06local Player = game.Players.LocalPlayer
07CarSeat:GetPropertyChangedSignal("Occupant"):Connect(function (humanoid) -- Checking that there is a person in the driver seat
08    if CarSeat.Occupant then -- Occupant Exists
09        if CarSeat.Occupant.Parent.Name == script.Parent.Parent.Name then -- Person in the seat is the local player
10         game:GetService("UserInputService").InputBegan:connect(function(input) -- Input Began checks if the player presses anything and fires whenever the player does so.
11                if input.KeyCode == Enum.KeyCode.E then -- This detects for a "e" press.
12                    print("E is")
13                end
14                end)
15            end
View all 26 lines...

1 answer

Log in to vote
1
Answered by 5 years ago
Edited 5 years ago

This happens because connections don't last only as long as a condition is valid. Connections must be disconnected through their :Disconnect() method. This stops the connection from running again. This can be implemented in your script as well:

01local UserInputService = game:GetService("UserInputService")
02local Car = game.Workspace.Car
03local CarBase = Car.CarBase
04local CarMoving = Car.CarMoving
05local CarSeat = Car.Seat
06local Player = game.Players.LocalPlayer
07local Connection -- We don't want the scope of the if statements to trouble us
08local StopConnection
09 
10CarSeat:GetPropertyChangedSignal("Occupant"):Connect(function(humanoid)
11    if CarSeat.Occupant then -- Occupant Exists
12        if CarSeat.Occupant.Parent.Name == Player.Name then -- Verify player
13            Connection = game:GetService("UserInputService").InputBegan:Connect(function(input) -- New connectoin
14                if input.KeyCode == Enum.KeyCode.E then
15                    print("E is")
View all 30 lines...

P.S. Use Connect, not connect. connect() is deprecated.

0
I had to move the stop connections to when the user leaves the seat, but otherwise it works! Thanks! PoppyandNeivaarecute 134 — 5y
Ad

Answer this question