Unique Identifiers, connecting instances with scripts

A UID is a unique ID generated for every created entity. You can store it as an attribute.

Use case:
Let’s say you have an item class, of which we’ve instantiated an item object. The item holds an interactable component which has a part and a proximityPrompt. When triggered, you’ll want it to get the parent table of the interactable: the item, so it can be picked up. But how can you find the class, using only the object?

By storing the UID on the object, and storing every item in a table where the keys are the UIDs, we can very easily get our item using only the UID.

The easiest way to script a UID system, is to create a module which has an index value. Whenever the module is called, increase the index by 1 and return it.

local i = 0
return function()
  i+=1
  return i
end

Now, whenever we call UID(), we’ll get a unique identifier. Then we just store the items by their UID.

local UID = require(game.ReplicatedStorage.UID)

local items = {}

item.new = function()
    local self = {}
    self.UID = UID()
  
    -- ... (other properties and methods of the item)
  
    items[self.UID] = self
    return self
end


interactable.proximityPrompt.Triggered:Connect(function(player)
    local itemUID = interactable.UID
    local item = items[itemUID]

    -- Now 'item' refers to the item object associated with the triggered interactable
end)

The best use would be if you had an ItemManager, which was in charge of creating/destroying/returning items. You could just ask the ItemManager to return the item, based on the UID.

5 Likes

Thanks, this would be useful for NPCs since now i dont’ have to generate a GUID from HttpService.