Нам в эту систему нужно добавить возможность сделать кнопку просмотра манифеста: using…
- User
Нам в эту систему нужно добавить возможность сделать кнопку просмотра манифеста:
using System.Linq; using Content.Server.Administration; using Content.Server.EUI; using Content.Server.Station.Components; using Content.Server.Station.Systems; using Content.Server.StationRecords; using Content.Server.StationRecords.Systems; using Content.Shared.Administration; using Content.Shared.CCVar; using Content.Shared.CrewManifest; using Content.Shared.GameTicking; using Content.Shared.Roles; using Content.Shared.StationRecords; using Robust.Shared.Configuration; using Robust.Shared.Console; using Robust.Shared.Player; using Robust.Shared.Prototypes; using Robust.Shared.Utility;
namespace Content.Server.CrewManifest;
public sealed class CrewManifestSystem : EntitySystem { [Dependency] private readonly StationSystem _stationSystem = default!; [Dependency] private readonly StationRecordsSystem _recordsSystem = default!; [Dependency] private readonly EuiManager _euiManager = default!; [Dependency] private readonly IConfigurationManager _configManager = default!; [Dependency] private readonly IPrototypeManager _prototypeManager = default!;
/// <summary> /// Cached crew manifest entries. The alternative is to outright /// rebuild the crew manifest every time the state is requested: /// this is inefficient. /// </summary> private readonly Dictionary<EntityUid, CrewManifestEntries> _cachedEntries = new(); private readonly Dictionary<EntityUid, Dictionary<ICommonSession, CrewManifestEui>> _openEuis = new(); public override void Initialize() { SubscribeLocalEvent<AfterGeneralRecordCreatedEvent>(AfterGeneralRecordCreated); SubscribeLocalEvent<RecordModifiedEvent>(OnRecordModified); SubscribeLocalEvent<RecordRemovedEvent>(OnRecordRemoved); SubscribeLocalEvent<RoundRestartCleanupEvent>(OnRoundRestart); SubscribeNetworkEvent<RequestCrewManifestMessage>(OnRequestCrewManifest); SubscribeLocalEvent<CrewManifestViewerComponent, BoundUIClosedEvent>(OnBoundUiClose); SubscribeLocalEvent<CrewManifestViewerComponent, CrewManifestOpenUiMessage>(OpenEuiFromBui); } private void OnRoundRestart(RoundRestartCleanupEvent ev) { foreach (var (_, euis) in _openEuis) { foreach (var (_, eui) in euis) { eui.Close(); } } _openEuis.Clear(); _cachedEntries.Clear(); } private void OnRequestCrewManifest(RequestCrewManifestMessage message, EntitySessionEventArgs args) { if (args.SenderSession is not { } sessionCast || !_configManager.GetCVar(CCVars.CrewManifestWithoutEntity)) { return; } OpenEui(GetEntity(message.Id), sessionCast); } // Not a big fan of this one. Rebuilds the crew manifest every time // somebody spawns in, meaning that at round start, it rebuilds the crew manifest // wrt the amount of players readied up. private void AfterGeneralRecordCreated(AfterGeneralRecordCreatedEvent ev) { BuildCrewManifest(ev.Key.OriginStation); UpdateEuis(ev.Key.OriginStation); } private void OnRecordModified(RecordModifiedEvent ev) { BuildCrewManifest(ev.Key.OriginStation); UpdateEuis(ev.Key.OriginStation); } private void OnRecordRemoved(RecordRemovedEvent ev) { BuildCrewManifest(ev.Key.OriginStation); UpdateEuis(ev.Key.OriginStation); } private void OnBoundUiClose(EntityUid uid, CrewManifestViewerComponent component, BoundUIClosedEvent ev) { if (!Equals(ev.UiKey, component.OwnerKey)) return; var owningStation = _stationSystem.GetOwningStation(uid); if (owningStation == null || !TryComp(ev.Actor, out ActorComponent? actorComp)) { return; } CloseEui(owningStation.Value, actorComp.PlayerSession, uid); } /// <summary> /// Gets the crew manifest for a given station, along with the name of the station. /// </summary> /// <param name="station">Entity uid of the station.</param> /// <returns>The name and crew manifest entries (unordered) of the station.</returns> public (string name, CrewManifestEntries? entries) GetCrewManifest(EntityUid station) { var valid = _cachedEntries.TryGetValue(station, out var manifest); return (valid ? MetaData(station).EntityName : string.Empty, valid ? manifest : null); } private void UpdateEuis(EntityUid station) { if (_openEuis.TryGetValue(station, out var euis)) { foreach (var eui in euis.Values) { eui.StateDirty(); } } } private void OpenEuiFromBui(EntityUid uid, CrewManifestViewerComponent component, CrewManifestOpenUiMessage msg) { if (!msg.UiKey.Equals(component.OwnerKey)) { Log.Error( "{User} tried to open crew manifest from wrong UI: {Key}. Correct owned is {ExpectedKey}", msg.Actor, msg.UiKey, component.OwnerKey); return; } var owningStation = _stationSystem.GetOwningStation(uid); if (owningStation == null || !TryComp(msg.Actor, out ActorComponent? actorComp)) { return; } if (!_configManager.GetCVar(CCVars.CrewManifestUnsecure) && component.Unsecure) { return; } OpenEui(owningStation.Value, actorComp.PlayerSession, uid); } /// <summary> /// Opens a crew manifest EUI for a given player. /// </summary> /// <param name="station">Station that we're displaying the crew manifest for.</param> /// <param name="session">The player's session.</param> /// <param name="owner">If this EUI should be 'owned' by an entity.</param> public void OpenEui(EntityUid station, ICommonSession session, EntityUid? owner = null) { if (!HasComp<StationRecordsComponent>(station)) { return; } if (!_openEuis.TryGetValue(station, out var euis)) { euis = new(); _openEuis.Add(station, euis); } if (euis.ContainsKey(session)) { return; } var eui = new CrewManifestEui(station, owner, this); euis.Add(session, eui); _euiManager.OpenEui(eui, session); eui.StateDirty(); } /// <summary> /// Closes an EUI for a given player. /// </summary> /// <param name="station">Station that we're displaying the crew manifest for.</param> /// <param name="session">The player's session.</param> /// <param name="owner">The owner of this EUI, if there was one.</param> public void CloseEui(EntityUid station, ICommonSession session, EntityUid? owner = null) { if (!HasComp<StationRecordsComponent>(station)) { return; } if (!_openEuis.TryGetValue(station, out var euis) || !euis.TryGetValue(session, out var eui)) { return; } if (eui.Owner == owner) { euis.Remove(session); eui.Close(); } if (euis.Count == 0) { _openEuis.Remove(station); } } /// <summary> /// Builds the crew manifest for a station. Stores it in the cache afterwards. /// </summary> /// <param name="station"></param> private void BuildCrewManifest(EntityUid station) { var iter = _recordsSystem.GetRecordsOfType<GeneralStationRecord>(station); var entries = new CrewManifestEntries(); var entriesSort = new List<(JobPrototype? job, CrewManifestEntry entry)>(); foreach (var recordObject in iter) { var record = recordObject.Item2; var entry = new CrewManifestEntry(record.Name, record.JobTitle, record.JobIcon, record.JobPrototype); _prototypeManager.TryIndex(record.JobPrototype, out JobPrototype? job); entriesSort.Add((job, entry)); } entriesSort.Sort((a, b) => { var cmp = JobUIComparer.Instance.Compare(a.job, b.job); if (cmp != 0) return cmp; return string.Compare(a.entry.Name, b.entry.Name, StringComparison.CurrentCultureIgnoreCase); }); entries.Entries = entriesSort.Select(x => x.entry).ToArray(); _cachedEntries[station] = entries; }}
[AdminCommand(AdminFlags.Admin)] public sealed class CrewManifestCommand : IConsoleCommand { public string Command => "crewmanifest"; public string Description => "Opens the crew manifest for the given station."; public string Help => $"Usage: {Command} ";
[Dependency] private readonly IEntityManager _entityManager = default!; public CrewManifestCommand() { IoCManager.InjectDependencies(this); } public void Execute(IConsoleShell shell, string argStr, string[] args) { if (args.Length != 1) { shell.WriteLine($"Invalid argument count.\n{Help}"); return; } if (!NetEntity.TryParse(args[0], out var uidNet) || !_entityManager.TryGetEntity(uidNet, out var uid)) { shell.WriteLine($"{args[0]} is not a valid entity UID."); return; } if (shell.Player == null || shell.Player is not { } session) { shell.WriteLine("You must run this from a client."); return; } var crewManifestSystem = _entityManager.System<CrewManifestSystem>(); crewManifestSystem.OpenEui(uid.Value, session); } public CompletionResult GetCompletion(IConsoleShell shell, string[] args) { if (args.Length != 1) { return CompletionResult.Empty; } var stations = new List<CompletionOption>(); var query = _entityManager.EntityQueryEnumerator<StationDataComponent>(); while (query.MoveNext(out var uid, out _)) { var meta = _entityManager.GetComponent<MetaDataComponent>(uid); stations.Add(new CompletionOption(uid.ToString(), meta.EntityName)); } return CompletionResult.FromHintOptions(stations, null); }}
Чтобы вот сюда можно было добавить:
- type: UserInterface
interfaces:
enum.SiliconLawsUiKey.Key:
type: SiliconLawBoundUserInterface
requireInputValidation: false
enum.BorgUiKey.Key:
type: BorgBoundUserInterface
enum.StrippingUiKey.Key:
type: StrippableBoundUserInterface
Only used for NT borgs that can switch type, defined here to avoid copy-pasting the rest of this component.
enum.BorgSwitchableTypeUiKey.SelectBorgType: type: BorgSelectTypeUserInterface enum.StationMapUiKey.Key: type: StationMapBoundUserInterface requireInputValidation: false - type: ActivatableUI key: enum.BorgUiKey.Key
- type: SiliconLawBound
- type: ActionGrant
actions:
- ActionViewLaws
- ActionPAIOpenMap
Или вот такое сделать:
- type: entity
id: ActionSelectBorgType
name: Select Cyborg Type
components:
- type: InstantAction itemIconStyle: NoItem icon: sprite: Interface/Actions/actions_borg.rsi state: select-type event: !type:BorgToggleSelectTypeEvent useDelay: 0.5
- type: UserInterface
interfaces:
enum.SiliconLawsUiKey.Key:
type: SiliconLawBoundUserInterface
requireInputValidation: false
enum.BorgUiKey.Key:
type: BorgBoundUserInterface
enum.StrippingUiKey.Key:
type: StrippableBoundUserInterface
- Assistant
Чтобы добавить возможность просмотра манифеста через интерфейс пользователя и создать соответствующую кнопку в системе, необходимо внести изменения в YAML конфигурации, а также в сам код. Для начала создадим новую UI-компоненту и добавим её в систему.
Шаг 1: Добавление нового типа UI
Если вы хотите добавить кнопку для просмотра манифеста в интерфейс, можно создать определение интерфейса в YAML файле конфигурации, аналогично тому, как это делается для других UI.
- type: UserInterface interfaces: enum.CrewManifestUiKey.Key: # Добавляем новый ключ интерфейса type: CrewManifestBoundUserInterface requireInputValidation: falseШаг 2: Настройка компонентов
Создайте новый компонент для управления интерфейсом:
- type: entity id: CrewManifestViewerComponent name: Crew Manifest Viewer components: - type: BoundUserInterface uiKey: enum.CrewManifestUiKey.KeyШаг 3: Добавление действия для кнопки
Добавьте действие, которое будет вызывать просмотр манифеста:
- type: entity id: ActionViewCrewManifest name: View Crew Manifest components: - type: InstantAction itemIconStyle: NoItem icon: sprite: Interface/Actions/actions_crew_manifest.rsi state: view event: !type:ViewCrewManifestEvent useDelay: 0.5Шаг 4: Обработка события и вызов интерфейса
Теперь в коде вам нужно добавить обработчик для этого нового события.
Добавьте новую подкоманду в system:
[RegisterEvent] public sealed class ViewCrewManifestEvent : EventArgs { public EntityUid Station { get; } public ICommonSession Session { get; } public ViewCrewManifestEvent(EntityUid station, ICommonSession session) { Station = station; Session = session; } } public override void Initialize() { ... SubscribeNetworkEvent<ViewCrewManifestEvent>(OnViewCrewManifest); } private void OnViewCrewManifest(ViewCrewManifestEvent msg) { OpenEui(msg.Station, msg.Session); }Шаг 5: Создание действия на кнопке
Теперь вам нужно сделать так, чтобы при нажатии на кнопку осуществлялся вызов
ViewCrewManifestEvent, например, в вашем UI компоненте:private void OnButtonPressed(EntityUid uid, CrewManifestViewerComponent component) { if (TryComp<ActorComponent>(component.Owner, out var actorComp)) { EntityManager.EventBus.RaiseEvent(new ViewCrewManifestEvent(GetOwningStation(uid), actorComp.PlayerSession)); } }Шаг 6: Обновление логики UI
В вашей UI логике (например, в
CrewManifestEui), обработайте соответствующие сообщения и обновите интерфейс манифеста, если он открыт.Заключение
Теперь, после внесения вышеперечисленных изменений, у вас должна появиться возможность открывать манифест с помощью интерфейса через добавленную кнопку. Убедитесь, что вы перепроверили все зависимости и правильно зарегистрировали новые события и компоненты.
- User
Можешь всё вписать в систему и скинуть готовое?
- Assistant
Конечно! Вот обновлённый код системы
CrewManifestSystem, который включает в себя новый интерфейс для просмотра манифеста, созданный на основе ваших требований:using System.Linq; using Content.Server.Administration; using Content.Server.EUI; using Content.Server.Station.Components; using Content.Server.Station.Systems; using Content.Server.StationRecords; using Content.Server.StationRecords.Systems; using Content.Shared.Administration; using Content.Shared.CCVar; using Content.Shared.CrewManifest; using Content.Shared.GameTicking; using Content.Shared.Roles; using Content.Shared.StationRecords; using Robust.Shared.Configuration; using Robust.Shared.Console; using Robust.Shared.Player; using Robust.Shared.Prototypes; using Robust.Shared.Utility; namespace Content.Server.CrewManifest; public sealed class CrewManifestSystem : EntitySystem { [Dependency] private readonly StationSystem _stationSystem = default!; [Dependency] private readonly StationRecordsSystem _recordsSystem = default!; [Dependency] private readonly EuiManager _euiManager = default!; [Dependency] private readonly IConfigurationManager _configManager = default!; [Dependency] private readonly IPrototypeManager _prototypeManager = default!; private readonly Dictionary<EntityUid, CrewManifestEntries> _cachedEntries = new(); private readonly Dictionary<EntityUid, Dictionary<ICommonSession, CrewManifestEui>> _openEuis = new(); public override void Initialize() { SubscribeLocalEvent<AfterGeneralRecordCreatedEvent>(AfterGeneralRecordCreated); SubscribeLocalEvent<RecordModifiedEvent>(OnRecordModified); SubscribeLocalEvent<RecordRemovedEvent>(OnRecordRemoved); SubscribeLocalEvent<RoundRestartCleanupEvent>(OnRoundRestart); SubscribeNetworkEvent<RequestCrewManifestMessage>(OnRequestCrewManifest); SubscribeLocalEvent<CrewManifestViewerComponent, BoundUIClosedEvent>(OnBoundUiClose); SubscribeLocalEvent<CrewManifestViewerComponent, CrewManifestOpenUiMessage>(OpenEuiFromBui); SubscribeNetworkEvent<ViewCrewManifestEvent>(OnViewCrewManifest); // Новое событие } private void OnRoundRestart(RoundRestartCleanupEvent ev) { foreach (var (_, euis) in _openEuis) { foreach (var (_, eui) in euis) { eui.Close(); } } _openEuis.Clear(); _cachedEntries.Clear(); } private void OnRequestCrewManifest(RequestCrewManifestMessage message, EntitySessionEventArgs args) { if (args.SenderSession is not { } sessionCast || !_configManager.GetCVar(CCVars.CrewManifestWithoutEntity)) { return; } OpenEui(GetEntity(message.Id), sessionCast); } private void AfterGeneralRecordCreated(AfterGeneralRecordCreatedEvent ev) { BuildCrewManifest(ev.Key.OriginStation); UpdateEuis(ev.Key.OriginStation); } private void OnRecordModified(RecordModifiedEvent ev) { BuildCrewManifest(ev.Key.OriginStation); UpdateEuis(ev.Key.OriginStation); } private void OnRecordRemoved(RecordRemovedEvent ev) { BuildCrewManifest(ev.Key.OriginStation); UpdateEuis(ev.Key.OriginStation); } private void OnBoundUiClose(EntityUid uid, CrewManifestViewerComponent component, BoundUIClosedEvent ev) { if (!Equals(ev.UiKey, component.OwnerKey)) return; var owningStation = _stationSystem.GetOwningStation(uid); if (owningStation == null || !TryComp(ev.Actor, out ActorComponent? actorComp)) { return; } CloseEui(owningStation.Value, actorComp.PlayerSession, uid); } public (string name, CrewManifestEntries? entries) GetCrewManifest(EntityUid station) { var valid = _cachedEntries.TryGetValue(station, out var manifest); return (valid ? MetaData(station).EntityName : string.Empty, valid ? manifest : null); } private void UpdateEuis(EntityUid station) { if (_openEuis.TryGetValue(station, out var euis)) { foreach (var eui in euis.Values) { eui.StateDirty(); } } } private void OpenEuiFromBui(EntityUid uid, CrewManifestViewerComponent component, CrewManifestOpenUiMessage msg) { if (!msg.UiKey.Equals(component.OwnerKey)) { Log.Error( "{User} tried to open crew manifest from wrong UI: {Key}. Correct owned is {ExpectedKey}", msg.Actor, msg.UiKey, component.OwnerKey); return; } var owningStation = _stationSystem.GetOwningStation(uid); if (owningStation == null || !TryComp(msg.Actor, out ActorComponent? actorComp)) { return; } if (!_configManager.GetCVar(CCVars.CrewManifestUnsecure) && component.Unsecure) { return; } OpenEui(owningStation.Value, actorComp.PlayerSession, uid); } public void OpenEui(EntityUid station, ICommonSession session, EntityUid? owner = null) { if (!HasComp<StationRecordsComponent>(station)) { return; } if (!_openEuis.TryGetValue(station, out var euis)) { euis = new(); _openEuis.Add(station, euis); } if (euis.ContainsKey(session)) { return; } var eui = new CrewManifestEui(station, owner, this); euis.Add(session, eui); _euiManager.OpenEui(eui, session); eui.StateDirty(); } public void CloseEui(EntityUid station, ICommonSession session, EntityUid? owner = null) { if (!HasComp<StationRecordsComponent>(station)) { return; } if (!_openEuis.TryGetValue(station, out var euis) || !euis.TryGetValue(session, out var eui)) { return; } if (eui.Owner == owner) { euis.Remove(session); eui.Close(); } if (euis.Count == 0) { _openEuis.Remove(station); } } private void BuildCrewManifest(EntityUid station) { var iter = _recordsSystem.GetRecordsOfType<GeneralStationRecord>(station); var entries = new CrewManifestEntries(); var entriesSort = new List<(JobPrototype? job, CrewManifestEntry entry)>(); foreach (var recordObject in iter) { var record = recordObject.Item2; var entry = new CrewManifestEntry(record.Name, record.JobTitle, record.JobIcon, record.JobPrototype); _prototypeManager.TryIndex(record.JobPrototype, out JobPrototype? job); entriesSort.Add((job, entry)); } entriesSort.Sort((a, b) => { var cmp = JobUIComparer.Instance.Compare(a.job, b.job); if (cmp != 0) return cmp; return string.Compare(a.entry.Name, b.entry.Name, StringComparison.CurrentCultureIgnoreCase); }); entries.Entries = entriesSort.Select(x => x.entry).ToArray(); _cachedEntries[station] = entries; } // Новый обработчик событий просмотра манифеста private void OnViewCrewManifest(ViewCrewManifestEvent msg) { OpenEui(msg.Station, msg.Session); } }Новый компонент и событие
Также добавьте следующее коды для новых компонентов и событий.
Новый компонент
CrewManifestViewerComponentpublic sealed class CrewManifestViewerComponent : Component { public string OwnerKey { get; set; } = default!; public bool Unsecure { get; set; } = false; // Для проверки на безопасность }Новое событие для просмотра манифеста
[RegisterEvent] public sealed class ViewCrewManifestEvent : EventArgs { public EntityUid Station { get; } public ICommonSession Session { get; } public ViewCrewManifestEvent(EntityUid station, ICommonSession session) { Station = station; Session = session; } }Обновление YAML конфигурации
Добавьте следующую конфигурацию в ваш YAML файл:
- type: UserInterface interfaces: enum.CrewManifestUiKey.Key: type: CrewManifestBoundUserInterface requireInputValidation: false - type: entity id: CrewManifestViewerComponent name: Crew Manifest Viewer components: - type: BoundUserInterface uiKey: enum.CrewManifestUiKey.Key - type: entity id: ActionViewCrewManifest name: View Crew Manifest components: - type: InstantAction itemIconStyle: NoItem icon: sprite: Interface/Actions/actions_crew_manifest.rsi state: view event: !type:ViewCrewManifestEvent useDelay: 0.5Заключение
Теперь, с этими изменениями, кнопка для просмотра манифеста должна корректно работать в вашем интерфейсе. Убедитесь, что все зависимости корректно настроены и протестируйте функциональность в вашем проекте.
- User
А куда мы делаем это событие?
- Assistant
Событие
ViewCrewManifestEventв коде системыCrewManifestSystemуже регистрируется в методеInitialize(), где мы подписываемся на его обработку с помощью методаSubscribeNetworkEvent<ViewCrewManifestEvent>(OnViewCrewManifest);. Вы просто должны убедиться, что это событие генерируется из правильного места в коде, чтобы инициировать просмотр манифеста.Генерация события
Ниже я покажу, где и как генерировать это событие. В этом контексте это может быть выполнено, например, в UI-компоненте, когда пользователь нажимает кнопку для просмотра манифеста.
Пример кода для генерации события
-
Создание кнопки в UI: Убедитесь, что в вашем пользовательском интерфейсе (например, для боргов или другого класса) добавлена кнопка, которая будет вызывать событие
ViewCrewManifestEvent. -
Генерация события в методе обработки кнопки: В UI-компоненте, отвечающем за отображение кнопки для просмотра манифеста, добавьте обработчик нажатия на кнопку. Вот пример кода, который можно использовать:
private void OnViewCrewManifestButtonPressed(EntityUid uid, CrewManifestViewerComponent component) { if (TryComp<ActorComponent>(component.Owner, out var actorComp)) { var owningStation = _stationSystem.GetOwningStation(uid); if (owningStation != null) { // Генерация события для открытия манифеста EntityManager.EventBus.RaiseEvent(new ViewCrewManifestEvent(owningStation.Value, actorComp.PlayerSession)); } } }Включение обработчика
Этот метод (
OnViewCrewManifestButtonPressed) вы должны связать с действием нажатия кнопки в пользовательском интерфейсе. Как это будет выглядеть, зависит от вашего механизма привязки событий в UI, но это может быть, например, вызов этого метода при нажатии на кнопку.Пример обертки в компоненте
Если у вас есть UI-компонент, отвечающий за управление манифестом, обработчик нажатия кнопки может выглядеть так:
public void Initialize() { // Здесь вы инициализируете UI и назначаете обработчики нажатия кнопок var viewButton = // получить ссылку на кнопку из UI viewButton.OnPressed += OnViewCrewManifestButtonPressed; }Подведение итогов
Итак, вам нужно:
- Убедиться, что у вас есть кнопка в вашем пользовательском интерфейсе.
- Добавить обработчик для этой кнопки, который будет вызывать
ViewCrewManifestEvent, передавая ему станцию и сессию игрока. - Система
CrewManifestSystemуже будет обрабатывать это событие через методOnViewCrewManifest, который вы добавили ранее.
Эти шаги должны позволить вам реализовать функциональность для открытия манифеста через кнопку в пользовательском интерфейсе.
-
- User
Я решительно не понимаю, куда и как это делать
- Assistant
Понял, давайте детализируем процесс создания события и интеграции его в вашу систему. Мы пройдёмся по всем необходимым шагам, чтобы вы могли реализовать функциональность кнопки для открытия манифеста в вашем проекте.
Шаг 1: Определение нового события
Сначала убедитесь, что вы определили
ViewCrewManifestEvent. Это событие будет использоваться для передачи данных о станции и сессии игрока в систему манифеста.[RegisterEvent] public sealed class ViewCrewManifestEvent : EventArgs { public EntityUid Station { get; } public ICommonSession Session { get; } public ViewCrewManifestEvent(EntityUid station, ICommonSession session) { Station = station; Session = session; } }Шаг 2: Регистрация обработчика в системе
Ваша система
CrewManifestSystemдолжна подписываться на это событие. Это уже сделано в методеInitialize:public override void Initialize() { // Добавляем обработчик события SubscribeNetworkEvent<ViewCrewManifestEvent>(OnViewCrewManifest); }Его реализация должна выглядеть как-то так:
private void OnViewCrewManifest(ViewCrewManifestEvent msg) { OpenEui(msg.Station, msg.Session); }Шаг 3: Создание кнопки в пользовательском интерфейсе
Теперь вам нужно будет добавить кнопку в пользовательский интерфейс (UI), которая будет вызывать событие
ViewCrewManifestEvent.Пример кода для UI-кнопки
Вместе с UI компонентом, он должен содержать обработчик нажатия кнопки, например:
public class CrewManifestButtonComponent : Component { private EntityUid? _station; // Ссылка на станцию // Метод для инициализации кнопки public void Initialize(EntityUid station) { _station = station; // Здесь вы связываете нажатие кнопки с вашим методом var button = /* Получить ссылку на кнопку */; // Предположим, у вас есть метод, который возвращает элемент кнопки button.OnPressed += OnViewCrewManifestButtonPressed; } private void OnViewCrewManifestButtonPressed() { // Получаем сессию игрока, который нажал кнопку if (OwnerManager.TryGetComponent<ActorComponent>(Owner, out var actor) && actor.PlayerSession != null) { // Генерируем событие var msg = new ViewCrewManifestEvent(_station.Value, actor.PlayerSession); EntityManager.EventBus.RaiseEvent(msg); } } }Шаг 4: Подключение UI к системе
Теперь вам нужно убедиться, что ваш UI-класс или функцию, которая отображает интерфейс, знает о кнопке и вызывает её инициализацию в подходящее время. Например:
private void OnViewCrewManifestButtonPressed(EntityUid uid, CrewManifestViewerComponent component) { // Извлечение UID станции var station = _stationSystem.GetOwningStation(uid); if (station != null) { // Генерируем событие для открытия манифеста var msg = new ViewCrewManifestEvent(station.Value, actorComp.PlayerSession); EntityManager.EventBus.RaiseEvent(msg); } }Шаг 5: Пример использования в UI
Когда вы инициализируете UI, например, в
CrewManifestEui, вы можете создать и связать кнопку:public class CrewManifestEui { // Код вашего EUI private void InitializeButtons() { var viewButton = /* Получить кнопку из интерфейса */; viewButton.OnPressed += () => { // Когда кнопка нажата, вызывается ваш метод OnViewCrewManifestButtonPressed(/* Передаем необходимые параметры */); }; } }Итог
- Определите событие
ViewCrewManifestEvent. - Подпишитесь на событие в
CrewManifestSystem. - Создайте кнопку в UI и назначьте на неё обработчик, который будет генерировать событие.
- Убедитесь, что кнопка связана с системой и может передавать данные о сессии игрока.
Эти шаги помогут вам интегрировать логику вызова манифеста в вашу систему. Если у вас всё ещё возникают вопросы, пожалуйста, дайте мне знать, и я помогу вам ещё больше!
- Определите событие