Press E to enter as a passenger

I am trying to make it so that you can enter the car as a passenger by pressing E to enter. At the moment it works to enter as a driver. Could somebody please help me and tell me what I need to add so that the press E to enter will work with passengers, not just as a driver?

local players = game:GetService("Players")
local runService = game:GetService("RunService")
local userInputService = game:GetService("UserInputService")

local carEnterGui = replicatedStorage.CarEnterGui

local Character = players.LocalPlayer.Character

local closestVehicle, gui, currentSeat


Character.Humanoid.Died:Connect(function()
    if gui then
        gui.Destroy()
    end
    script.Disabled = true
end)


userInputService.InputBegan:Connect(function(input)
    if input.KeyCode == Enum.KeyCode.F then
        if gui then
            gui.Parent:Sit(Character.Humanoid)
        elseif currentSeat then 
            currentSeat:Sit(nil)
            wait()
            Character.HumanoidRootPart.CFrame = Character.HumanoidRootPart.CFrame + Vector3.new(0, 12, 0)
        end
    end
end)

Character.Humanoid.Seated:Connect(function(active, currentSeatPart)
    if active then 
        currentSeat = currentSeatPart
    else
        currentSeat = nil
    end
end)

local toogleGui = function(toogle)
    if gui then
        gui:Destroy()
        gui = nil
    end

    if toogle == true then 
        gui = carEnterGui:Clone()
        gui.Parent = closestVehicle:FindFirstChildWhichIsA("VehicleSeat")
    end
end

runService.RenderStepped:Connect(function()
    local maxDistance = 10
    local newClosestVehicle

    for _, vehicle in pairs(workspace.Vehicles:GetChildren()) do
        if (vehicle.DriveSeat.Position - Character.HumanoidRootPart.Position).magnitude <= maxDistance and not vehicle.DriveSeat.Occupant then 
            maxDistance = (vehicle.DriveSeat.Position - Character.HumanoidRootPart.Position).magnitude
            newClosestVehicle = vehicle
        end
    end
    closestVehicle = newClosestVehicle

    if closestVehicle and not currentSeat then
        toogleGui(true)
    else
        toogleGui(false)
    end
end)```
3 Likes

Right now your code looks for the nearest vehicle and shows the GUI for that vehicle’s driver seat. Instead, look for all seats within vehicles and show the GUI for the nearest seat of any type. You’ll also have to modify the toggleGui function to instead parent the GUI to the nearest seat, not the first VehicleSeat in the nearest vehicle.

2 Likes

Hope it helps. It‘s faster and will only take ± 10 lines instead of over 100 lines.

2 Likes