Skip to content

Unique ID

To generate unique identifiers, the System.Guid class is usually used, because it provides a fast and reliable mechanism to generate IDs that are long enough for the collision chance to be almost zero.

However, this class is not serializable. That's why Game Creator comes with the UniqueID class, which serves two purposes:

  • Serializable: This means that any changes made to this ID will be kept between editor sessions.
  • Custom UI: When showing this ID in a Unity Window, it automatically displays a nice and handy box with buttons that allow you to easily modify this ID or even regenerate it, in case that's necessary.

Initialization

Initializing a UniqueID is as easy as calling its constructor. For example, let's say we want to add a unique ID to a MonoBehaviour class:

public class MyComponent : MonoBehaviour
{
    public UniqueID myID = new UniqueID();
}

This will automagically assign a unique ID to the myID field. If we drag and drop this component onto a scene game object, we'll see this field with its associated ID.

If you want to start from a specific identifier instead of a random one, use the constructor that accepts a string:

public UniqueID myID = new UniqueID("my-custom-id");

Accessing ID

The ID value can be accessed by getting the IdString struct, which contains a string based ID and its hash value. The hash value is recommended when comparing IDs:

To get the hash value:

int hash = this.myID.Get.Hash;

To get the string value:

string id = this.myID.Get.String;

Best Practices

Accessing the string value of the UniqueID should only be done if you plan on serializing this value somewhere. For comparing two IDs, it is best if you simply compare their hash value, as the probability that two different strings have the same hash value is very, very low. On the other hand, comparing two int values is extremely fast and performant.