Providing objects with unique IDs onStart

I have a gameObjects group in which I assign unique IDs in the Start function.

void Start() {
    UniqueID = String.Format("{0:X}", DateTime.Now.Ticks);
}

      

I thought it would work, but I get duplicate IDs from time to time. How can I make sure they are always unique?

+3


source to share


3 answers


Unity

already provide a unique ID for each instance of an object, see GetInstanceID .



+1


source


I would use guid.

UniqueID = Guid.NewGuid.ToString();

      



Using your suggestion, two instances running at the same time can apply the same "unique" unique identifier to two different objects.

The guide must be unique even on different occasions.

+6


source


This method does not provide a unique identifier for multiple instances of your application!

I suggest using a variable static long

and using Interlocked.Increment which handles concurrency and synchronization so you can assign Id to your objects easily. It is better than a GUID for debugging purposes and is more readable and uses less memory than a GUID.

//define an accessible static variable somewhere in your code
public static long __Id = 0;

//use it to assign unique Id to objects
UniqueID = Interlocked.Increment(ref __Id);

      

also its performance is better than GUID, here is a quick check and result

public static long __Id = 0;
private static void Main(string[] args)
{
    var sw1 = new Stopwatch();
    var guid = Guid.NewGuid();
    sw1.Start();
    for (var i = 0; i < 10000000; i++)
    {
        guid = Guid.NewGuid();
    }
    sw1.Stop();
    Console.WriteLine(guid);
    Console.WriteLine(sw1.ElapsedTicks);

    var sw2 = new Stopwatch();
    long id = 0;
    sw2.Start();
    for (var i = 0; i < 10000000; i++)
    {
        id = Interlocked.Increment(ref __Id);
    }
    sw2.Stop();
    Console.WriteLine(id);
    Console.WriteLine(sw2.ElapsedTicks);
}

      

and the result

f91419e0-9d3a-4e64-b7fd-ed2080dad599
10376104 (guide time)
10000000
304231 (long time) 34 times faster than guid

+3


source







All Articles