--!strict

local Players = game:GetService("Players")

local function GetPlayerFromInstance(instance: Instance, aliveOnly: boolean?): Player?
	for _, player: Player in ipairs(Players:GetPlayers()) do
		local character = player.Character::Model
		
		if not character or not character.Parent then
			continue
		end
		
		if aliveOnly == true then
			local humanoid = character:FindFirstChildOfClass("Humanoid")::Humanoid
			
			if not humanoid or humanoid.Health <= 0 or humanoid:GetState() == Enum.HumanoidStateType.Dead then
				continue
			end
		end
		
		if instance:IsDescendantOf(character) then
			return player
		end
	end
	
	return nil
end

return GetPlayerFromInstance
