I’m currently trying to create a FPS game that uses a loadout system where items are represented in a table. The current concern that I have is how I can access values of the loadout table if I wish to access it from another script/the server.
I was thinking of using modulescripts to implement this, but I don’t know how I can sync the information of the player’s loadout from server to client (vise versa) so the loadout remains the same per player, additionally, I don’t know how I can implement a unique loadout modulescript for multiple players in a server (since a modulescript would be considered a global object in replicatedstorage on the server)
If anyone has worked with FPS games before and know how to implement player loadouts that can be accessible by both the server and client for each player, I would appreciate your input alot. Thank you!
You can fire the player loadout table from the server to the client in a RemoteEvent and to save it to the DataStore we save the data as a string by encoding it in JSON using HttpService: HttpService | Documentation - Roblox Creator Hub
Example Server Script:
local DataStoreService = game:GetService("DataStoreService")
local HttpService = game:GetService("HttpService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Players = game:GetService("Players")
local LoadoutDataStore = DataStoreService:GetDataStore("playerLoadouts")
local playerLoadouts = {} -- { [player.UserId]: {Primary: string, Secondary: string, Equipment: string} }
--[[
Example:
playerLoadouts =
{
[123123123] = { Primary = "AK47", Secondary = "Pistol", Equipment = "Smoke Grenade" },
[456456] = { Primary = "Uzi", Secondary = "Katana", Equipment = "Flash Grenade" }
}
]]
local GetLoadoutRemote = Instance.new("RemoteEvent")
GetLoadoutRemote.Name = "GetLoadoutRemote"
GetLoadoutRemote.Parent = ReplicatedStorage
local function onPlayerAdded(player: Player)
local success, loadout = pcall(function()
return LoadoutDataStore:GetAsync(player.UserId)
end)
if success and type(loadout) == "string" then
playerLoadouts[player.UserId] = HttpService:JSONDecode(loadout)
else
-- Default loadout if none exists
playerLoadouts[player.UserId] = {
Primary = "DefaultGun",
Secondary = "DefaultPistol",
Equipment = "DefaultGrenade"
}
end
GetLoadoutRemote:FireClient(player, playerLoadouts[player.UserId])
end
for _, player in Players:GetPlayers() do
onPlayerAdded(player)
end
Players.PlayerAdded:Connect(onPlayerAdded)
GetLoadoutRemote.OnServerEvent:Connect(function(player: Player, newLoadout: any?)
GetLoadoutRemote:FireClient(player, playerLoadouts[player.UserId])
end)
local function onPlayerRemoving(player: Player)
pcall(function()
LoadoutDataStore:SetAsync(player.UserId, HttpService:JSONEncode(playerLoadouts[player.UserId]))
end)
playerLoadouts[player.UserId] = nil
end
Players.PlayerRemoving:Connect(onPlayerRemoving)