Skip to content

Instantly share code, notes, and snippets.

@joshcamas
Created March 22, 2019 06:50
Show Gist options
  • Save joshcamas/62e2049b21457347163dcea43b8caeae to your computer and use it in GitHub Desktop.
Save joshcamas/62e2049b21457347163dcea43b8caeae to your computer and use it in GitHub Desktop.
Unity3D Guid Saving
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
/*
* Saves custom GUID for a gameobject. Will automatically make sure
* there are no duplicates. Checks open scenes as well as prefabs
* By default, GUID is not saved when inside of a prefab asset.
*/
[ExecuteInEditMode, DisallowMultipleComponent]
public class GuidComponent : MonoBehaviour, ISerializationCallbackReceiver
{
//Cached Value
private System.Guid guid = System.Guid.Empty;
[SerializeField]
private byte[] serializedGuid;
//Whether to clear GUID's when this object is in a prefab asset
//If true, instantiating this object will create a new GUID. Otherwise,
//it will retain the GUID from before.
[SerializeField]
public bool clearIfPrefabAsset = true;
public System.Guid Guid
{
get
{
return guid;
}
set
{
guid = value;
serializedGuid = guid.ToByteArray();
}
}
public string GuidString
{
get { return Guid.ToString(); }
set { Guid = new System.Guid(value); }
}
private bool DisableSerialization()
{
#if UNITY_EDITOR
return (clearIfPrefabAsset && PrefabUtility.IsPartOfPrefabAsset(this));
#else
return false;
#endif
}
public void OnAfterDeserialize()
{
if (serializedGuid != null && serializedGuid.Length == 16)
guid = new System.Guid(serializedGuid);
}
public void OnBeforeSerialize()
{
#if UNITY_EDITOR
if (DisableSerialization())
{
serializedGuid = null;
guid = System.Guid.Empty;
}
#endif
}
public void CreateGuid()
{
Guid = System.Guid.NewGuid();
#if UNITY_EDITOR
if(!Application.isPlaying)
{
Undo.RecordObject(this, "GUID Creation");
if (PrefabUtility.IsPartOfVariantPrefab(this))
PrefabUtility.RecordPrefabInstancePropertyModifications(this);
UnityEditor.SceneManagement.EditorSceneManager.MarkSceneDirty(gameObject.scene);
}
#endif
}
void Awake()
{
//Automatically create a GUID if it is empty / invalid
if(serializedGuid == null || serializedGuid.Length != 16)
{
if (!DisableSerialization())
CreateGuid();
return;
}
#if UNITY_EDITOR
if (Application.isPlaying)
return;
//Scan all guid components
bool foundDuplicate = false;
foreach(GuidComponent gc in Resources.FindObjectsOfTypeAll<GuidComponent>())
{
if (gc == this)
continue;
if(gc.Guid.ToString() == Guid.ToString())
{
foundDuplicate = true;
break;
}
}
if(foundDuplicate)
CreateGuid();
#endif
}
}
using UnityEditor;
[CustomEditor(typeof(GuidComponent))]
class GuidComponentInspector : Editor
{
public override void OnInspectorGUI()
{
GuidComponent guidComp = (GuidComponent)target;
EditorGUILayout.SelectableLabel(guidComp.Guid.ToString());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment