I am aiming to make a script that can detect user input, but only be active when the player is in the seat. It doesn’t have to be the absolute best way to do it, just “work”. I also have a piece of code already prepared that if possible, could be built on the work this way.
LocalScript Code:
local UIS = game:GetService( "UserInputService" )
UIS.InputEnded:Connect(function(inputObject, gameProcessedEvent)
if inputObject.KeyCode == Enum.KeyCode.E then
print("Key E pressed")
game.ReplicatedStorage.MoveTrainFoward:FireServer()
end
end)
You can check if the seats occupant is the character, example:
local UIS = game:GetService( "UserInputService" )
local seat = game.Workspace.MySeat
local Players = game:GetService("Players")
local player = player.LocalPlayer
UIS.InputEnded:Connect(function(inputObject, gameProcessedEvent)
local char = player.Character or player.CharacterAdded:Wait()
if inputObject.KeyCode == Enum.KeyCode.E and seat.Occupant == char then
print("Key E pressed")
game.ReplicatedStorage.MoveTrainFoward:FireServer()
end
end)
ContextActionService would be more convenient in this case since you can bind/unbind actions for specific keys at a specific moment. You could still do this with UIS by disconnecting the InputBegan connection when you’re done with it, but InputBegan fires for any input, whereas using CAS you can bind a function to only fire for the E key as you sit down.
Adding onto this, you could use the context action service to bind and unbind keybinds.
You could hook the property changed event up to the seat to check when the occupant is changed. If an occupant is added, you will want to set the bind for them. If an occupant is removed, you will want to remove the bind for them.
local CAS = game:GetService("ContextActionService")
function action(name, state)
-- do your magic
-- you can check InputEnded and InputBegan with the "state", take a look at the documentation for that
end
humanoid.Seated:Connect(function(seated, seat)
if seated then
CAS:BindAction("yourAction", action, Enum.KeyCode.LeftShift) -- you can change LeftShift to anything
else
CAS:UnbindAction("yourAction")
end
end)
I would recommend using the ContextActionService too
local UIS = game:GetService( "UserInputService" )
local Seat = workspace.Seat
local player = game.Players.LocalPlayer
UIS.InputEnded:Connect(function(inputObject, gameProcessedEvent)
if inputObject.KeyCode == Enum.KeyCode.E and (Seat.Occupant or workspace):IsDescendantOf(player.Character) then
print("Key E pressed")
game.ReplicatedStorage.MoveTrainFoward:FireServer()
end
end)