/// --------------------------------------------- /// Behavior Designer /// Copyright (c) Opsive. All Rights Reserved. /// https://www.opsive.com /// --------------------------------------------- namespace Opsive.BehaviorDesigner.Samples { using System; using Unity.Collections; using Unity.Entities; using UnityEngine; using UnityEngine.UI; /// /// Displays entity spawn button and information. /// public class EntitySpawnerUI : MonoBehaviour { [Tooltip("A reference to the spawn data.")] [SerializeField] protected EntitySpawnData m_SpawnData; [Tooltip("A reference to the entity count text.")] [SerializeField] protected Text m_Text; /// /// Creates the EntityCountSystem. /// private void Start() { var entityCountSystem = World.DefaultGameObjectInjectionWorld.GetOrCreateSystemManaged(); entityCountSystem.OnUpdateEntityCount += (int count) => { m_Text.text = $"Entity Count: {count}"; }; var systemGroup = World.DefaultGameObjectInjectionWorld.GetOrCreateSystemManaged(); systemGroup.AddSystemToUpdateList(entityCountSystem); } /// /// Spawns a new set of entity agents. /// public void Spawn() { var entityManager = World.DefaultGameObjectInjectionWorld.EntityManager; var query = new EntityQueryBuilder(Allocator.Temp).WithAll().Build(entityManager); var spawnerEntity = query.ToEntityArray(AllocatorManager.Temp); // Only one entity will be returned. This entity was created within EntitySpawner.Baker. var entitySpawnerPrefab = entityManager.GetComponentData(spawnerEntity[0]); entityManager.SetComponentData(spawnerEntity[0], new SpawnData() { Prefab = entitySpawnerPrefab.Prefab, SpawnCount = m_SpawnData.AdditiveSpawnCount, MinRadius = m_SpawnData.MinRadius, MaxRadius = m_SpawnData.MaxRadius, MinRotationSpeed = m_SpawnData.MinRotationSpeed, MaxRotationSpeed = m_SpawnData.MaxRotationSpeed, }); spawnerEntity.Dispose(); query.Dispose(); // EntitySpawnerSystem disables itself. Enable it to allow for the spawn. World.DefaultGameObjectInjectionWorld.Unmanaged.GetExistingSystemState().Enabled = true; } /// /// Shows the agent entity count. /// [DisableAutoCreation] private partial class EntityCountSystem : SystemBase { [Tooltip("Event sent when the entity count is updated.")] public Action OnUpdateEntityCount; private EntityQuery m_EntityCountQuery; /// /// Caches the entity count query. /// protected override void OnCreate() { m_EntityCountQuery = new EntityQueryBuilder(Allocator.Temp).WithAll().Build(EntityManager); } /// /// Updates the entity count. /// protected override void OnUpdate() { var agentEntities = m_EntityCountQuery.ToEntityArray(WorldUpdateAllocator); OnUpdateEntityCount?.Invoke(agentEntities.Length); agentEntities.Dispose(); } /// /// Destroys the cached the entity count query. /// protected override void OnDestroy() { m_EntityCountQuery.Dispose(); } } } }