1
0

MobStateActionsSystem.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. using Content.Shared.Actions;
  2. using Content.Shared.Mobs.Components;
  3. namespace Content.Shared.Mobs.Systems;
  4. /// <summary>
  5. /// Adds and removes defined actions when a mob's <see cref="MobState"/> changes.
  6. /// </summary>
  7. public sealed class MobStateActionsSystem : EntitySystem
  8. {
  9. [Dependency] private readonly SharedActionsSystem _actions = default!;
  10. /// <inheritdoc/>
  11. public override void Initialize()
  12. {
  13. SubscribeLocalEvent<MobStateActionsComponent, MobStateChangedEvent>(OnMobStateChanged);
  14. SubscribeLocalEvent<MobStateComponent, ComponentInit>(OnMobStateComponentInit);
  15. }
  16. private void OnMobStateChanged(EntityUid uid, MobStateActionsComponent component, MobStateChangedEvent args)
  17. {
  18. ComposeActions(uid, component, args.NewMobState);
  19. }
  20. private void OnMobStateComponentInit(EntityUid uid, MobStateComponent component, ComponentInit args)
  21. {
  22. if (!TryComp<MobStateActionsComponent>(uid, out var mobStateActionsComp))
  23. return;
  24. ComposeActions(uid, mobStateActionsComp, component.CurrentState);
  25. }
  26. /// <summary>
  27. /// Adds or removes actions from a mob based on mobstate.
  28. /// </summary>
  29. private void ComposeActions(EntityUid uid, MobStateActionsComponent component, MobState newMobState)
  30. {
  31. if (!TryComp<ActionsComponent>(uid, out var action))
  32. return;
  33. foreach (var act in component.GrantedActions)
  34. {
  35. Del(act);
  36. }
  37. component.GrantedActions.Clear();
  38. if (!component.Actions.TryGetValue(newMobState, out var toGrant))
  39. return;
  40. foreach (var id in toGrant)
  41. {
  42. EntityUid? act = null;
  43. if (_actions.AddAction(uid, ref act, id, uid, action))
  44. component.GrantedActions.Add(act.Value);
  45. }
  46. }
  47. }