-
-
Save creativitRy/19599b7b332d80ec6126175b4ae8f2fa to your computer and use it in GitHub Desktop.
Entity UUID
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[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