Script that changes player health while in a seat

I’ve been working on a script that changes the player health when sitting in a seat in order to create what appears to be an armored vehicle on Roblox. The script, however, does not operate after being placed inside a seat.

Here is a script that I attempted to use.


local seat = script.Parent
local player = seat.Occupant
local healthIncreaseAmount = 600


local function increaseHealth()
    if player and player.Character then
        local humanoid = player.Character:FindFirstChild("Humanoid")
        if humanoid then
            humanoid.Health = humanoid.Health + healthIncreaseAmount
        end
    end
end


local function onOccupantChanged()
    player = seat.Occupant
    if player then
        increaseHealth()
    end
end


if seat.Occupant then
    onOccupantChanged()
end


seat:GetPropertyChangedSignal("Occupant"):Connect(onOccupantChanged)

I am also trying to change the player’s health back to normal (100) when they exit the seat.

I believe you need to set their max health to 600, then set their health to 600 as well

The moment player sits into the seat, seat.Occupant becomes occupied with player’s humanoid. Because occupant becomes nil once there’s no player in the seat, we have to store the reference ourselves. In the appended script I did this with an object value called OccupantVal inside the seat.

Other than that, as @tore2513 said, health won’t grow over max health.

I added some comments in the script. For ease of use, I reference individual seat via script.Parent, though you may want to modify the code to fit your framework.

Script
local Players = game:GetService("Players")

local HEALTH_INCREASE_AMOUNT = 600

local seat = script.Parent
local occupantVal = seat.OccupantVal

local function increaseHealth()
	occupantVal.Value.MaxHealth += HEALTH_INCREASE_AMOUNT
	occupantVal.Value.Health += HEALTH_INCREASE_AMOUNT
end

local function decreaseHealth()
	occupantVal.Value.MaxHealth -= HEALTH_INCREASE_AMOUNT
	
	-- If the health was below 100, reset to 100 would increase
	-- the player's health, thus we leave it unchanged in that case.
	if occupantVal.Value.Health > 100 then
		occupantVal.Value.Health = 100
	end
end

local function onOccupantChanged()
	if seat.Occupant then
		-- Is the occupant a player?
		if Players:GetPlayerFromCharacter(seat.Occupant.Parent) then
			occupantVal.Value = seat.Occupant -- update our value
			increaseHealth()
		end
	else
		if not occupantVal.Value then return; end
		decreaseHealth()
		occupantVal.Value = nil -- update our value
	end
end

seat:GetPropertyChangedSignal("Occupant"):Connect(onOccupantChanged)
2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.