Checking for a character when a player leaves

im tryna check so if a player left the game with a forcefield then something happens but i cant even reach the part where it checks for the character

i tried to do it like this:

Players.PlayerRemoving:Connect(function(Player)
	print("player left")
	if Player.Character and Player.Character.Humanoid then
		print("there is a character and a humanoid")
	end
end)

but it doesnt even print the character and humanoid check

1 Like

You could give the player object a BoolValue. The BoolValue represents whether the forcfield is on, or not. When the player leaves, you can save the value to a DataStore. When the player rejoins, fetch the data from the DataStore. If the value is true, you should be able to run whatever you need to there.

1 Like

thats actually a good idea i was just thinking about that, thanks!

1 Like
local Game = game
local Players = Game:GetService("Players")

local function OnPlayerAdded(Player)
	local function OnCharacterRemoving(Character)
		
	end
	
	Player.CharacterRemoving:Connect(OnCharacterRemoving)
end

Players.PlayerAdded:Connect(OnPlayerAdded)

‘CharacterRemoving’ fires when a player leaves.

local Game = game
local Players = Game:GetService("Players")
local DataStoreService = Game:GetService("DataStoreService")
local ForceFieldStore = DataStoreService:GetDataStore("ForceFieldStore")

local Characters = {}

local function OnPlayerAdded(Player)
	local Character = Player.Character or Player.CharacterAdded:Wait()
	Characters[Player] = Character
	
	local Success, Result = pcall(function() return ForceFieldStore:GetAsync(Player.UserId) end)
	if not Success then warn(Result) return end
	if not Result then return end
	--Do something if result.
end

local function OnPlayerRemoving(Player)
	local ForceField = if Characters[Player] and Characters[Player]:FindFirstChild("ForceField") then true else false
	Characters[Player] = nil
	local Success, Result = pcall(function() return ForceFieldStore:SetAsync(Player.UserId, ForceField) end)
	if not Success then warn(Result) end
end

Players.PlayerAdded:Connect(OnPlayerAdded)
Players.PlayerRemoving:Connect(OnPlayerRemoving)
2 Likes