using Unity.Burst;
using Unity.Entities;
using Unity.Mathematics;
using Unity.Transforms;
using UnityEngine;
partial struct SpawnerSystem : ISystem
{
[BurstCompile]
public void OnCreate(ref SystemState state) { }
[BurstCompile]
public void OnDestroy(ref SystemState state) { }
[BurstCompile]
public void OnUpdate(ref SystemState state)
{
EntityCommandBuffer.ParallelWriter ecb = GetEntityCommandBuffer(ref state);
new ProcessSpawnerJob
{
ElapsedTime = SystemAPI.Time.ElapsedTime,
Ecb = ecb,
}.ScheduleParallel();
}
private EntityCommandBuffer.ParallelWriter GetEntityCommandBuffer(ref SystemState state)
{
var ecbSingleton = SystemAPI.GetSingleton<BeginSimulationEntityCommandBufferSystem.Singleton>();
var ecb = ecbSingleton.CreateCommandBuffer(state.WorldUnmanaged);
return ecb.AsParallelWriter();
}
[BurstCompile]
public partial struct ProcessSpawnerJob : IJobEntity
{
public EntityCommandBuffer.ParallelWriter Ecb;
public double ElapsedTime;
private void Execute([ChunkIndexInQuery] int chunkIndex, ref Spawner spawner)
{
int row = 2;
int column = 2;
int height = 2;
float3 baseScale = new float3(1, 1, 1); // Base scale
// Scale reduction factor per level
if (spawner.NextSpawnTime < ElapsedTime)
{
for (float scaleFactor = 0.5f; scaleFactor >= 0.0125; scaleFactor /= 2 )
{
for (int h = 0; h < height; h++)
{
for (int j = 0; j < column; j++)
{
for (int k = 0; k < row; k++)
{
Entity newEntity = Ecb.Instantiate(chunkIndex, spawner.Prefab);
// Calculate position
float xPos = baseScale.x / 4 * math.pow(-1, k);
float yPos = baseScale.y / 4 * math.pow(-1, j);
float zPos = baseScale.z / 4 * math.pow(-1, h);
// Set position and scale
float3 spawnPosition = spawner.SpawnPosition + new float3(xPos, yPos, zPos);
Ecb.SetComponent(chunkIndex, newEntity, LocalTransform.FromPositionRotationScale(spawnPosition, quaternion.identity, scaleFactor));
}
}
}
}
// Update next spawn time
spawner.NextSpawnTime = (float)ElapsedTime + spawner.SpawnRate;
}
}
}
}
This creates 8 cubes for every scale but I need like octree based decomposition like (2)(n)(3) number of cubes n is the grid depth. First Scale of 1 creates 8 cubes which as a scale of 0.5 and then its child creates 8 cubes of its own kind and continues till the end of the grid depth. It is easier to create in Unity OOPS but implementation is difficult in Unity DOTS. I need some suggestions or solutions ??