Skip to content

Instantly share code, notes, and snippets.

@samloeschen
Last active January 18, 2023 04:15
Show Gist options
  • Save samloeschen/327ff9b252ddf71de422a62909ff10ce to your computer and use it in GitHub Desktop.
Save samloeschen/327ff9b252ddf71de422a62909ff10ce to your computer and use it in GitHub Desktop.
GlobalID
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using UnityEngine;
using Object = UnityEngine.Object;
// This is a System.Guid, except it can be serialized by Unity,
// so it can be used to permanently store the ID of an entity.
[Serializable, StructLayout(LayoutKind.Explicit)]
public struct GlobalID : IEquatable<GlobalID> {
[FieldOffset(0), NonSerialized] public Guid guid;
[FieldOffset(0), SerializeField] public long guidPart1;
[FieldOffset(8), SerializeField] public long guidPart2;
public static GlobalID GenerateNewID() {
return new GlobalID {
guid = Guid.NewGuid()
};
}
public bool IsSet() {
return guidPart1 != 0 || guidPart2 != 0;
}
public override string ToString() {
return guid.ToString();
}
public static bool TryParse(string guidString, out GlobalID result) {
if (Guid.TryParse(guidString, out Guid guid)) {
result = new GlobalID {
guid = guid
};
return true;
} else {
result = default;
return false;
}
}
public bool Equals(GlobalID other) {
return guid.Equals(other.guid);
}
public override bool Equals(object other) {
if (other is GlobalID otherID) {
return guid.Equals(otherID.guid);
}
return false;
}
public static bool operator ==(GlobalID lhs, GlobalID rhs) {
return lhs.guid == rhs.guid;
}
public static bool operator !=(GlobalID lhs, GlobalID rhs) {
return lhs.guid != rhs.guid;
}
public static bool operator >(GlobalID lhs, GlobalID rhs) {
if (lhs.guidPart1 == rhs.guidPart1) {
return lhs.guidPart2 > rhs.guidPart2;
}
return lhs.guidPart1 > rhs.guidPart1;
}
public static bool operator <(GlobalID lhs, GlobalID rhs) {
if (lhs.guidPart1 == rhs.guidPart1) {
return lhs.guidPart2 < rhs.guidPart2;
}
return lhs.guidPart1 < rhs.guidPart1;
}
public override int GetHashCode() {
return guidPart1.GetHashCode() * 31 + guidPart2.GetHashCode();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment