im using this script to spawn a large amount of entities at a selected spawn point, it works flawlessly except (what seems like the very first frame) a red entity is spawned at 0,0,0 unmoving and i have no idea why
using Authoring;
using Authoring.Enemies;
using Unity.Burst;
using Unity.Collections;
using Unity.Entities;
using Unity.Transforms;
using UnityEngine;
namespace Systems.Enemies
{
[UpdateBefore(typeof(EnemyMovementSystem))]
public partial struct EnemySpawnSystem : ISystem
{
private EntityQuery enemySpawnPointQuery;
//private EntityQuery activeEnemiesQuery;
private float spawnTimer;
private EntityCommandBuffer ecb;
public void OnCreate(ref SystemState state)
{
enemySpawnPointQuery = state.GetEntityQuery(
ComponentType.ReadOnly<LocalTransform>(),
ComponentType.ReadOnly<EnemySpawner>()
);
// activeEnemiesQuery = state.GetEntityQuery(
// ComponentType.ReadOnly<EnemyMover>()
// );
ecb = new EntityCommandBuffer(Allocator.Persistent);
state.RequireForUpdate<EntityReferences>();
state.RequireForUpdate(enemySpawnPointQuery);
}
[BurstCompile]
public void OnUpdate(ref SystemState state)
{
EntityReferences entityReferences = SystemAPI.GetSingleton<EntityReferences>();
Entity enemyPrefab = entityReferences.enemyPrefabEntity;
ecb = new EntityCommandBuffer(Allocator.TempJob);
EntityCommandBuffer.ParallelWriter parallelEcb = ecb.AsParallelWriter();
//int enemyCount = activeEnemiesQuery.CalculateEntityCount();
//Debug.Log($"There are currently {enemyCount} enemies.");
EnemySpawnerJob enemySpawnerJob = new EnemySpawnerJob
{
deltaTime = SystemAPI.Time.DeltaTime,
commandBuffer = parallelEcb,
enemyPrefab = enemyPrefab
};
state.Dependency = enemySpawnerJob.ScheduleParallel(enemySpawnPointQuery, state.Dependency);
state.Dependency.Complete();
ecb.Playback(state.EntityManager);
ecb.Dispose();
}
public void OnDestroy(ref SystemState state)
{
if (ecb.IsCreated)
ecb.Dispose();
}
}
[BurstCompile]
public partial struct EnemySpawnerJob : IJobEntity
{
public float deltaTime;
public EntityCommandBuffer.ParallelWriter commandBuffer;
public Entity enemyPrefab;
public void Execute([EntityIndexInQuery] int entityIndex, in LocalTransform localTransform, ref EnemySpawner enemySpawner)
{
Entity enemyEntity = commandBuffer.Instantiate(entityIndex, enemyPrefab);
commandBuffer.AddComponent(entityIndex, enemyEntity, new EnemyMover
{
moveSpeed = 3f,
rotationSpeed = 10f
});
commandBuffer.SetComponent(entityIndex, enemyEntity, LocalTransform.FromPosition(localTransform.Position));
}
}
}