Skip to content

Instantly share code, notes, and snippets.

@creativitRy
Last active August 9, 2019 07:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save creativitRy/19599b7b332d80ec6126175b4ae8f2fa to your computer and use it in GitHub Desktop.
Save creativitRy/19599b7b332d80ec6126175b4ae8f2fa to your computer and use it in GitHub Desktop.
Entity UUID
[DisallowMultipleComponent]
[ExecuteAlways]
public class Entity : MonoBehaviour
{
private static readonly Dictionary<EntityUuid, Entity> Entities = new Dictionary<EntityUuid, Entity>();
public EntityUuid Uuid;
private void Awake()
{
if (Application.isPlaying)
{
Uuid = ParseUuidFromName();
Entities.Add(Uuid, this);
}
}
public EntityUuid ParseUuidFromName()
{
if (Uuid.IsExplicit)
{
return Uuid;
}
var entityName = gameObject.name;
if (entityName.EndsWith("@"))
{
var startIndex = entityName.LastIndexOf('@', entityName.Length - 2) + 1;
var uuidStr = entityName.Substring(startIndex, entityName.Length - startIndex - 1);
return EntityUuid.Parse(uuidStr);
}
var uuid = Uuid;
if (Entities.ContainsKey(Uuid))
uuid = new EntityUuid(null);
gameObject.name = entityName + " @" + uuid + "@";
return uuid;
}
#if UNITY_EDITOR
private void Start()
{
if (!Application.isPlaying)
{
ValidateName();
Entities[Uuid] = this;
}
}
#endif
private void ValidateName()
{
#if UNITY_EDITOR
if (Application.isPlaying)
return;
if (Uuid.IsExplicit)
return;
var go = gameObject;
if (go.IsPrefabObject())
return;
var prevName = go.name;
if (Regex.IsMatch(prevName, @"^.* @[A-Za-z0-9\-]+@ \(\d+\)$"))
{
var updatedName = prevName.Substring(0, prevName.LastIndexOf('@',
prevName.LastIndexOf('@') - 1) - 1) + " @" +
new EntityUuid(null) + "@";
go.name = updatedName;
UnityEditor.SceneManagement.EditorSceneManager.MarkSceneDirty(go.scene);
}
else if (!prevName.EndsWith("@"))
{
go.name = prevName + " @" + new EntityUuid(null) + "@";
}
#endif
}
private void OnDestroy()
{
if (Application.isPlaying)
{
Entities.Remove(Uuid);
}
else
{
Entities.Remove(ParseUuidFromName());
}
}
public override string ToString()
{
return Uuid.ToString();
}
// ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment