// When de-serializing or creating this component, we want to either restore our serialized GUID // or create a new one. void CreateGuid() { // if our serialized data is invalid, then we are a new object and need a new GUID if (serializedGuid == null || serializedGuid.Length != 16) { #if UNITY_EDITOR // if in editor, make sure we aren't a prefab of some kind if (IsAssetOnDisk()) { return; } Undo.RecordObject(this, "Added GUID"); #endif guid = Guid.NewGuid(); serializedGuid = guid.ToByteArray(); #if UNITY_EDITOR // If we are creating a new GUID for a prefab instance of a prefab, but we have somehow lost our prefab connection // force a save of the modified prefab instance properties if (PrefabUtility.IsPartOfNonAssetPrefabInstance(this)) { PrefabUtility.RecordPrefabInstancePropertyModifications(this); } #endif } else if (guid == Guid.Empty) { // otherwise, we should set our system guid to our serialized guid guid = new Guid(serializedGuid); } // register with the GUID Manager so that other components can access this if (guid != Guid.Empty) { if (!GuidManagerSingleton.Add(guid, gameObject)) { // if registration fails, we probably have a duplicate or invalid GUID, get us a new one. RegenerateGuid(); } } }
/// <summary> /// Sets guid. Be careful with this method. It should be called only in specific cases. /// </summary> /// <param name="value">New guid</param> public void SetGuid(Guid value) { cachedStringGuid = null; Guid?oldGuid = null; if (IsGuidAssigned()) { oldGuid = guid; GuidManagerSingleton.Remove(guid); } guid = value; if (!GuidManagerSingleton.Add(guid, gameObject)) { Debug.LogError($"Trying to set invalid guid: {value}. Previous guid restored."); if (oldGuid.HasValue) { guid = oldGuid.Value; GuidManagerSingleton.Add(guid, gameObject); } } }