{"id":17754661,"url":"https://github.com/catcodegames/commands","last_synced_at":"2025-10-04T10:20:31.064Z","repository":{"id":258030951,"uuid":"861823592","full_name":"CatCodeGames/Commands","owner":"CatCodeGames","description":"Command Pattern and Command Queue for Unity","archived":false,"fork":false,"pushed_at":"2024-10-20T21:08:22.000Z","size":34,"stargazers_count":3,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2024-10-21T01:38:49.597Z","etag":null,"topics":["csharp","unity","unity-package","unity3d"],"latest_commit_sha":null,"homepage":"","language":"C#","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/CatCodeGames.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-09-23T15:12:43.000Z","updated_at":"2024-10-20T21:08:26.000Z","dependencies_parsed_at":"2024-10-21T00:40:10.238Z","dependency_job_id":null,"html_url":"https://github.com/CatCodeGames/Commands","commit_stats":null,"previous_names":["catcodegames/commands"],"tags_count":2,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/CatCodeGames%2FCommands","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/CatCodeGames%2FCommands/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/CatCodeGames%2FCommands/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/CatCodeGames%2FCommands/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/CatCodeGames","download_url":"https://codeload.github.com/CatCodeGames/Commands/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":222749363,"owners_count":17031913,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["csharp","unity","unity-package","unity3d"],"created_at":"2024-10-26T14:07:55.743Z","updated_at":"2025-10-04T10:20:26.026Z","avatar_url":"https://github.com/CatCodeGames.png","language":"C#","funding_links":[],"categories":[],"sub_categories":[],"readme":"# 1. Description\nThis repository contains a base class and interface for the Command pattern. It also includes classes for sequential and parallel execution of commands. The Command pattern simplifies request management by encapsulating them as objects. Using a command queue allows you to build a sequence of requests, helping to avoid callback hell. This is particularly useful for creating complex sequences of actions, such as effects and animations, ensuring cleaner and more manageable code.\n[Tutorial on YouTube](https://www.youtube.com/watch?v=WAFlLeRxbFE) \n\n# 2. How to use\n### 2.1 Creating a Command\nTo create a new command, you need to inherit from the Command class.\n- The OnExecute method initiates the command’s working logic.\n- The OnStop method handles the cancellation of the command and releases resources.\n- The Continue method is called after the working logic is completed, which finalizes the command and changes its state to finished.\nHere is an example of a command that waits for a button click:\n``` csharp\n public sealed class WaitButtonClick : Command\n {\n     private readonly Button _button;\n\n     public WaitButtonClick(Button button)\n     {\n         _button = button;\n     }\n\n     protected override void OnExecute()\n     {\n         // Start listening for button clicks when the command is executed.\n         _button.onClick.AddListener(OnButtonClick);\n     }\n     \n     protected override void OnStop()\n     {\n         // Unsubscribe from the event when the command is stopped.\n         _button.onClick.RemoveListener(OnButtonClick);\n     }\n\n     private void OnButtonClick()\n     {\n         // Unsubscribe from the button click event to prevent further processing.\n         _button.onClick.RemoveListener(OnButtonClick);\n         // Finish the command.\n         Continue();\n     }\n }\n```\n### 2.2 Using the Command\n``` csharp\n// Create the command and subscribe to events\nvar cmd = new WaitButtonClick(_button)\n  .AddOnStarted(() =\u003e Debug.Log(\"Command started\"))\n  .AddOnStopped(() =\u003e Debug.Log(\"Command stopped\"))\n  .AddOnFinished(() =\u003e Debug.Log(\"Command finished\"));\n// Execute the command\ncmd.Execute();\t    \n```\n### 2.3 Command Queue\nThe command queue executes commands sequentially, waiting for each to complete before starting the next one.\n- ExecuteOnAdd allows commands to be dynamically added to the queue and executed as they are added.\n- The CommandAddMode parameter specifies whether a command should be added to the beginning (Next) or the end (Last) of the queue. By default, commands are added to the end of the queue.\n``` csharp\nvar queue = new CommandQueue()\n  .SetExecuteOnAdd(false)\n  .Add(cmd, CommandAddMode.Next)\n  .Add(WaitCommand.FromSeconds(1))\n  // add other commands\n  // ...\n  .AddOnStarted(() =\u003e Debug.Log(\"Command queue started\"))\n  .AddOnFinished(() =\u003e Debug.Log(\"Command queue finished\"));\nqueue.Execute();\n```\n\n### 2.4 CommandGroup\n\nA command group executes all specified commands simultaneously and waits for their completion.\n``` csharp\nvar group = new CommandGroup()\n  .Add(cmd)\n  .Add(WaitCommand.FromSeconds(1))\n  // add other commands\n  // ...\n  .AddOnFinished(() =\u003e Debug.Log(\"All commands completed\"));\ngroup.Execute();\n```\n         \n### 2.5 Комбинирование\nBoth the command queue and command group implement the ICommand interface, allowing them to be used as commands within other groups and queues.\n``` csharp\nvar queue= new CommandQueue()\n  .Add(new CommandGroup()\n  .Add(new CommandQueue())\n  .Add(new CommandQueue()))\n  .Add(new CommandGroup());\nqueue.Execute();\n```\n\n\n\n# 1. Описание \nЭтот репозиторий содержит базовый класс и интерфейс для паттерна “Команда”. В нем также представлены классы для последовательного и одновременного выполнения команд. Паттерн “Команда” упрощает управление запросами, инкапсулируя их в виде объектов. Использование очереди команд позволяет набирать последовательность запросов, помогая избежать “callback hell”. Это особенно полезно для создания сложных последовательностей действий, таких как эффекты и анимации, обеспечивая более чистый и управляемый код.\n[Видео-туториал на YouTube](https://www.youtube.com/watch?v=WAFlLeRxbFE) \n\n# 2. Использование\n### 2.1 Создание команды\nДля новой команды нужно наследоваться от класса Command.\n- Метод **OnExecute** запускает рабочую логику команды.\n- Метод **OnStop** обрабатывает отмену выполнения команды и освобождает ресурсы.\n- Метод **Continue** вызывается после завершения рабочей логики, что приводит к завершению выполнения команды и изменению её состояния на завершённое.\nПример команды, ожидающий нажатия на кнопку\n``` csharp\n public sealed class WaitButtonClick : Command\n {\n     private readonly Button _button;\n\n     public WaitButtonClick(Button button)\n     {\n         _button = button;\n     }\n\n     protected override void OnExecute()\n     {\n         // При запуске команды начинаем отслеживать нажатие на кнопку.\n         _button.onClick.AddListener(OnButtonClick);\n     }\n     \n     protected override void OnStop()\n     {\n         // При отмене запущенной команды, необходимо отписаться от события            \n         _button.onClick.RemoveListener(OnButtonClick);\n     }\n\n     private void OnButtonClick()\n     {\n         // Отписываемся от события нажатия на кнопку,\n         // чтобы предотвратить дальнейшую обработку нажатий.\n         _button.onClick.RemoveListener(OnButtonClick);\n         // Завершаем выполнение команды.\n         Continue();\n     }\n }\n```\n### 2.2 Использование команды\n``` csharp\n// создание команды и подписка на события\nvar cmd = new WaitButtonClick(_button)\n  .AddOnStarted(() =\u003e Debug.Log(\"Команда запущена\"))\n  .AddOnStopped(() =\u003e Debug.Log(\"Команда прервана\"))\n  .AddOnFinished(() =\u003e Debug.Log(\"Команда завершена\"));\n// запуск выполнения команды\ncmd.Execute();\t    \n```\n\n### 2.3 Очередь команд\nОчередь команда запускает команды последовательно друг за другом, дожидаясь завершения предыдущей. \n- **ExecuteOnAdd** позволяет добавлять команды в очередь динамически и выполнять их по мере добавления.\n- Параметр **CommandAddMode** определяет,будет ли команда добавляться в начало (Next) или конец (Last) очереди. По умолчанию команда всегда добавляется к конец очереди\n``` csharp\nvar queue = new CommandQueue()\n  .SetExecuteOnAdd(false)\n  .Add(cmd, CommandAddMode.Next)\n  .Add(WaitCommand.FromSeconds(1))\n  // добавление других команд\n  // ...\n  .AddOnStarted(() =\u003e Debug.Log(\"Очередь команд запущена\"))\n  .AddOnFinished(() =\u003e Debug.Log(\"Очередь команд завершена\"));\nqueue.Execute();\n```\n\n### 2.4 Группа команд\n\nГруппа команда одновременно запускает все указанные команды и ожидает их завершения.\n``` csharp\nvar group = new CommandGroup()\n  .Add(cmd)\n  .Add(WaitCommand.FromSeconds(1))\n  // добавление других команд\n  // ...\n  .AddOnFinished(() =\u003e Debug.Log(\"Все команды завершены\"));\ngroup.Execute();\n```\n         \n### 2.5 Комбинирование\nОчередь команда и группа команд реализуют интерфейс ICommand, что позволяет их самих использовать как команды в группах и очередях\n``` csharp\nvar queue= new CommandQueue()\n  .Add(new CommandGroup()\n  .Add(new CommandQueue())\n  .Add(new CommandQueue()))\n  .Add(new CommandGroup());\nqueue.Execute();\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcatcodegames%2Fcommands","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fcatcodegames%2Fcommands","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcatcodegames%2Fcommands/lists"}