Help With Database System

Hello,

I’m currently working on a custom username system. However, I’m struggling figuring out how it would work. How I would go about making a Database System without the use of external services?

(I need it to be able to read and write data)

have you read this?

I believe you asked for this before.

Here’s a quick system I wrote which appears to be working.

local players = game:GetService("Players")
local datastores = game:GetService("DataStoreService")
local datastore = datastores:GetDataStore("NameStore")

local function onPlayerAdded(player)
	local function onPlayerChatted(message)
		local split = message:split(" ")
		if #split >= 2 then
			if split[1]:lower():match("^%pname") then
				if split[2]:len() >= 3 and split[2]:len() <= 20 then
					local success, result = pcall(function()
						return datastore:UpdateAsync(game.GameId, function(data)
							data = data or {}
							for id, name in pairs(data) do
								if split[2] == name then
									return data
								end
							end
							
							data[tostring(player.UserId)] = split[2]
							player.leaderstats.Username.Value = split[2]
							return data
						end)
					end)
					
					if success then
						if result then
							print(result)
						end
					else
						warn(result)
					end
				end
			end
		end
	end
	
	player.Chatted:Connect(onPlayerChatted)
	
	local leaderstats = Instance.new("Folder")
	leaderstats.Name = "leaderstats"
	leaderstats.Parent = player
	
	local nameValue = Instance.new("StringValue")
	nameValue.Name = "Username"
	nameValue.Value = ""
	nameValue.Parent = leaderstats
	
	local success, result = pcall(function()
		return datastore:GetAsync(game.GameId)
	end)
	
	if success then
		if result then
			if type(result) == "table" then
				nameValue.Value = result[tostring(player.UserId)] or ""
			end
		end
	end
end

players.PlayerAdded:Connect(onPlayerAdded)

Names are displayed via the built-in leaderstats, duplicate names are disallowed and previous usernames are made available again such that anyone can take them.

1 Like