/// <summary> /// On ESPDU. /// </summary> /// <param name="es"></param> private void OnEntityState(Header h) { EntityState es = h as EntityState; // Does the entity already exist? RemoteEntity re; if (!RemoteEntities.TryGetValue(es.EntityID.HashCode, out re)) { // Create a new entity using the entity map. GameObject foundGO = entityMap.GetMatch(es.EntityType); if (foundGO != null) { re = CreateEntity(foundGO, es); Debug.Log(string.Format("Discovered new entity: Name - {0}, ID - {1}", es.Marking.ASCII, es.EntityID)); } else { Debug.LogWarning(string.Format("Could not create object {0}. Not found in entity map.", es.EntityType.ToString())); return; } } else { // Update entity re.UpdateEntity(es); re.LastUpdate = Time.timeSinceLevelLoad; } // Has the entity been deactivated? if (!es.Appearance.State) { RemoveEntity(re, true); } }
/// <summary> /// Remove a entity from the sim and fire events. /// </summary> /// <param name="e"></param> /// <param name="destroy">Destroy the entity?</param> private void RemoveEntity(Entity e, bool destroy) { if (e is RemoteEntity) { Debug.Log(string.Format("Removing entity: {0}({1})", e.State.Marking.ASCII, e.State.EntityID)); if (RemoteEntities.Remove(e.ID.HashCode)) { removeRemoteEntity.Invoke(e as RemoteEntity); } else { return; } } else { if (LocalEntites.Remove(e.ID.HashCode)) { removeLocalEntity.Invoke(e as LocalEntity); } else { return; } } removeEntity.Invoke(e); if (destroy) { Destroy(e.gameObject); } }
/// <summary> /// Creates a new remote entity from an entity state pdu /// </summary> /// <param name="from">GameObject to use, from entity map.</param> /// <param name="es">The entity state pdu.</param> /// <returns></returns> private RemoteEntity CreateEntity(GameObject from, EntityState es) { GameObject entityGO = Instantiate(from) as GameObject; RemoteEntity re = entityGO.GetComponent <RemoteEntity>() ?? entityGO.AddComponent <RemoteEntity>(); RemoteEntities.Add(es.EntityID.HashCode, re); // Add new entity re.Init(es); // Fire events newEntity.Invoke(re); newRemoteEntity.Invoke(re); // Start periodic checks, if the entity is not updated within the HeartBeat duration then it will be removed from the sim. re.LastUpdate = Time.timeSinceLevelLoad; StartCoroutine(TimeoutRemoteEntity(re)); if (remoteEntityParent != null) { entityGO.transform.parent = remoteEntityParent.transform; } return(re); }