Skip to content

Instantly share code, notes, and snippets.

@simonwittber
Last active May 10, 2021 12:38
Show Gist options
  • Save simonwittber/a3e6666ced23d23594ba50c08e8057a4 to your computer and use it in GitHub Desktop.
Save simonwittber/a3e6666ced23d23594ba50c08e8057a4 to your computer and use it in GitHub Desktop.
A pattern to implement a scheduler in Unity DOTS.
using Unity.Collections;
using Unity.Entities;
using Unity.Jobs;
namespace PatternsOfDots
{
/// <summary>
/// Add a WaitForSeconds component to your entity with a delay parameter.
/// The ScheduleSystem will then wait that many seconds before removing
/// the component, and add a Ready tag component. You can then process
/// the Ready component in your own systems.
/// </summary>
public struct WaitForSeconds : IComponentData
{
public float time;
public WaitForSeconds(float delay) => this.time = UnityEngine.Time.time + delay;
}
public struct Ready : IComponentData { }
public class ScheduleSystem : ComponentSystem
{
protected override void OnUpdate()
{
var now = UnityEngine.Time.time;
Entities.ForEach<WaitForSeconds>((Entity e, ref WaitForSeconds s) =>
{
if (s.time <= now)
{
PostUpdateCommands.RemoveComponent<WaitForSeconds>(e);
PostUpdateCommands.AddComponent<Ready>(e, new Ready());
}
});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment