How can i improve character loading here?

How can i improve the character loading part of the code?

--> Top
local _L = require(game.ReplicatedStorage:WaitForChild("Framework"):WaitForChild("Library"))
local _S = _L.Services

--> Constants


--> Variables


-----------------------------------------------
_L.Network.new("RemoteEvent", "CreateComponentClient")
_L.Network.new("RemoteEvent", "ActivatedWeaponServer")
_L.Network.new("RemoteEvent", "PopupClient")

_S.Players.PlayerAdded:Connect(function(player)
	local newPlayer = _L.Player.new(player)
	_L.Directory.Game.Players[player] = newPlayer
	
	local RefreshCharacter = function(character)
		task.spawn(function()
			while not character:IsDescendantOf(game.Workspace) do
				character.AncestryChanged:Wait()
			end

			_L.PlayerBillboard.new(player, character)
		end)

		task.spawn(function()
			newPlayer:RefreshWeapons()
		end)
	end
	
	local character = player.Character or player.CharacterAdded:Wait()
	RefreshCharacter(character)
	
	player.CharacterAdded:Connect(function(character)
		RefreshCharacter(character)
	end)
end)

_S.Players.PlayerRemoving:Connect(function(player)
	_L.Directory.Game.Players[player] = nil
end)
3 Likes

You shouldn’t need

local character = player.Character or player.CharacterAdded:Wait()
RefreshCharacter(character)

and

player.CharacterAdded:Connect(function(character)
	RefreshCharacter(character)
end)

The second part should work on its own as long as there is no wait before connecting the event. Also, you shouldn’t use task.spawn unless you absolutely have to.

1 Like