How could I save a gun preset?

I want to make a system where players can select a gun, optic, rails, muzzles, etc. How would I do this? First of all, what would be the best way to store these selected attachments so I can save this. Should I make a folder with every attachment’s statistic and model, then make an string value to save that about everything?

I’d make a module that would act like a HashMap which would link all attachments (like a string for an unique name) to an instance or something, then make a module to set player’s choice and then use DataStores to save the data using HttpService:JSONEncode.

This can be achieved with code like this:

-- AttachmentRegistry.lua

local module = {}

local attachments = {}

function module.RegisterAttachment(attachment: Instance)
	local uniqueId = attachment:GetAttribute("AttachmentID")
	
	attachments[uniqueId] = attachment
end

function module.GetAttachment(uniqueId: string)
	return attachments[uniqueId] or nil
end

return module
-- PlayerAttachmentSetup.lua

local module = {}

local AttachmentRegistry = require(script.Parent.AttachmentRegistry)

local playerAttachments = {}

local function getAttachments(player: Player)
	local setup = playerAttachments[player.UserId]
	
	if not setup then
		playerAttachments[player.UserId] = {}
	end
	
	return setup or {}
end

local function attachmentExists(id: string) -- chech whether the attachment exists, if not - throw an error
	local attachment = AttachmentRegistry.GetAttachment(id)

	if not attachment then
		error("Attachment " .. id .. " does not exist")
	end

	return true
end

function module.GetPlayerAttachmentSetup(player: Players) -- returns the player's setup for saving
	return getAttachments(player)
end

function module.SetMuzzle(player: Player, id: string)
	attachmentExists(id)
	
	local attachments = getAttachments(player)
	
	attachments["Muzzle"] = id;
end

function module.SetBarrel(player: Player, id: barrel)
	attachmentExists(id)
	
	local attachments = getAttachments(player);
	
	attachments["Barrel"] = id
end

return module

1 Like