Why does the Roblox FPS template do this?

Why does the FPS template use separate variables for the ammo and reloading state of the gun instead of just using the attributes (so that way it’s always synced)?

function BlasterController.new(blaster: Tool)
	local self = {
		ammo = blaster:GetAttribute(Constants.AMMO_ATTRIBUTE),
		reloading = blaster:GetAttribute(Constants.RELOADING_ATTRIBUTE),
end

Instead of keeping it as a seperate variable, you can just access the attribute’s value whenever you need it. What is the point of handling it as a separate variable?

Yeah, I understand what you mean but there is a few advantages to using variables.

  • GetAttribute is slightly slower than reading from a local variable and in high performance FPS games where ammo can be checked every single frame the overhead could matter.
  • It’s cleaner because it allows them to make changes locally like deducting ammo by 1 and only push the update to the attribute when it is required - avoids constantly reading and writing to the Instance.

Read this: Attributes are 4x slower than other reads

1 Like

To follow up I have a question:

Is doing this faster,

local magSize = tool:GetAttribute("MagazineSize")
print(magSize)

than doing this?

print(tool:GetAttribute("MagazineSize"))

or is that just a styling thing people do

The first is faster it the attribute doesn’t change and you are accessing it multiple times.

Whilst the bottom one is best if you are only accessing once and the attribute changes often.

If you’re relying on the variable and not continuing to update and fetch the attribute then yes., the first one is faster.

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