Lag spike upon equipping tool

I’m experiencing a lag spike whenever I equip a tool in my game.
https://gyazo.com/6c8ea1e5b011ee49c003b9029a978ab2

I somewhat modified Roblox’s tool and I don’t use Welds. Instead, I use a Motor6D in torso. I use character.ChildAdded and check is it a Tool, if yes, I’ll process the child to this function:

function UpdateTool(newchar, Tool)
	WeaponTool = Tool
	Remotes.ConnectM6D:FireServer(Tool.BodyAttach)
	
	coroutine.wrap(function()
		WeaponToolStats = FindWeaponStats(Tool.Name)		
		offset = CFrame.new(WeaponToolStats.adsoffset_X,WeaponToolStats.adsoffset_Y, WeaponToolStats.adsoffset_Z)
	
		Animations.Idle = hum:LoadAnimation(Tool.Animations.IdleAnim)
		Animations.Idle2 = hum:LoadAnimation(Tool.Animations.Idle2Anim)
		Animations.Equip = hum:LoadAnimation(Tool.Animations.EquipAnim)
		Animations.Shoot = hum:LoadAnimation(Tool.Animations.ShootAnim)
		Animations.Reload = hum:LoadAnimation(Tool.Animations.ReloadAnim)
			
		UIP.MouseIconEnabled = false
		Animations.Idle:Play()
		Animations.Equip:Play()
		newchar.Torso.ToolGrip.Part1 = Tool.BodyAttach
		WeaponToolStats.CurrentAccuracy = WeaponToolStats.BaseAccuracy
		
	end)()
	return
end

Is there any problem with this code causing such function? This is stored inside a client starter script.
WeaponToolStats is an table with stats and FindWeaponStats is a function that find out the corresponding stats in the table.

FindWeaponStats:

function FindWeaponStats(ToolString)
	for i,v in pairs (Weapons) do
		if v.WeaponName == ToolString then
			return v
		end
	end
	return
end
1 Like

I would personally assume this is less so as a result of script lag and more-so rendering lag, however I admit I could be incorrect on that, the M6D could also be a potential culprit.

Nevertheless, seeing as how insignificant the lag spike is, it doesn’t seem to be greatly effecting game play, if no fix is presented by someone w/ more experience than me in the subject, I see no reason not to leave it as-is.

I think maybe it’s not related on the code that I’ve posted, even if I change it to something like print(), it still had a sight lag.

I found an older version of my game where it doesn’t have this problem. My older version use a PlayerGui script, which means the script resets and initialize every time when player spawns. But I’ve replace such method with a StarterScripts which acts the opposite.

In my old practise: I’ll do

char.ChildAddeed
If tool then
UpdateTool(child)
end

Now:

function OffSpawn(char)

char.ChildAddeed
If tool then
UpdateTool(child)
end

end

player.CharacterAdded(char)
Offspawn(char)

I’m not sure is this related? Btw the spike looks insignificant, but for some reasons, I don’t know why the longer the player stay, the more lag they will get upon equip. Maybe Memory Leak?

Nevermind, I solved it. It’s because I have another module script which runs a heavy function upon DescendantAdded.

2 Likes