Update: You do not actually require HttpService in game settingsto be enabled to use GenerateGUID, this is just missing in documentation. I’m keeping the original post below for archival reasons, and if anyone wants to implement custom seed uuids or something like this outside of Roblox.
Original Post:
Recently I ran into a situation where I needed to generate unique IDs for objects within an experience. Roblox has a method to do this with the GenerateGUID function. However, this requires HttpServices to be enabled under the security section of game settings. I didn’t know if the experience I was making this for would have this enabled, so I created my own module to replicate the functionality of this without needing HttpService enabled.
The below code is written to be used within a Roblox ModuleScript
local Generator = {}
Generator.__index = Generator
export type Class = typeof(setmetatable({}:: {
_seed: IntValue?
}, Generator))
function Generator.GenerateUUID(self: Class, wrapInCurlyBraces: boolean?)
if self._seed then
math.randomseed(self._seed)
end
local template ='xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'
if wrapInCurlyBraces then
template = '{' .. template .. '}'
end
return string.gsub(template, '[xy]', function (c)
local v = (c == 'x') and math.random(0, 0xf) or math.random(8, 0xb)
return string.format('%x', v)
end)
end
function Generator.CreateUniqueSeed(self: Class)
-- Is this number random? No. However, we can use this to our advantage as the current time will never be the same again
self._seed = os.time()
end
function Generator.SetSeed(self: Class, Seed: number)
self._seed = Seed
end
return Generator