SpawnerSystem.cs 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. using System.Threading;
  2. using Content.Server.Spawners.Components;
  3. using Robust.Shared.Random;
  4. namespace Content.Server.Spawners.EntitySystems;
  5. public sealed class SpawnerSystem : EntitySystem
  6. {
  7. [Dependency] private readonly IRobustRandom _random = default!;
  8. public override void Initialize()
  9. {
  10. base.Initialize();
  11. SubscribeLocalEvent<TimedSpawnerComponent, ComponentInit>(OnSpawnerInit);
  12. SubscribeLocalEvent<TimedSpawnerComponent, ComponentShutdown>(OnTimedSpawnerShutdown);
  13. }
  14. private void OnSpawnerInit(EntityUid uid, TimedSpawnerComponent component, ComponentInit args)
  15. {
  16. component.TokenSource?.Cancel();
  17. component.TokenSource = new CancellationTokenSource();
  18. uid.SpawnRepeatingTimer(TimeSpan.FromSeconds(component.IntervalSeconds), () => OnTimerFired(uid, component), component.TokenSource.Token);
  19. }
  20. private void OnTimerFired(EntityUid uid, TimedSpawnerComponent component)
  21. {
  22. if (!_random.Prob(component.Chance))
  23. return;
  24. var number = _random.Next(component.MinimumEntitiesSpawned, component.MaximumEntitiesSpawned);
  25. var coordinates = Transform(uid).Coordinates;
  26. for (var i = 0; i < number; i++)
  27. {
  28. var entity = _random.Pick(component.Prototypes);
  29. SpawnAtPosition(entity, coordinates);
  30. }
  31. }
  32. private void OnTimedSpawnerShutdown(EntityUid uid, TimedSpawnerComponent component, ComponentShutdown args)
  33. {
  34. component.TokenSource?.Cancel();
  35. }
  36. }