{"id":21585320,"url":"https://github.com/catcodegames/singleton","last_synced_at":"2026-02-28T14:31:13.697Z","repository":{"id":261700229,"uuid":"885054609","full_name":"CatCodeGames/Singleton","owner":"CatCodeGames","description":"Basic Singleton pattern implementation for Unity with flexible creation and configuration options.","archived":false,"fork":false,"pushed_at":"2024-11-12T02:19:48.000Z","size":29,"stargazers_count":2,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-04-10T20:22:58.513Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"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,"zenodo":null}},"created_at":"2024-11-07T21:47:53.000Z","updated_at":"2024-11-12T02:19:52.000Z","dependencies_parsed_at":"2024-11-08T00:26:36.053Z","dependency_job_id":"916588cb-d273-4c3d-9c45-48fe3fd3b3c1","html_url":"https://github.com/CatCodeGames/Singleton","commit_stats":null,"previous_names":["catcodegames/singleton"],"tags_count":1,"template":false,"template_full_name":null,"purl":"pkg:github/CatCodeGames/Singleton","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/CatCodeGames%2FSingleton","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/CatCodeGames%2FSingleton/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/CatCodeGames%2FSingleton/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/CatCodeGames%2FSingleton/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/CatCodeGames","download_url":"https://codeload.github.com/CatCodeGames/Singleton/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/CatCodeGames%2FSingleton/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":281712930,"owners_count":26548727,"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","status":"online","status_checked_at":"2025-10-29T02:00:06.901Z","response_time":59,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"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":[],"created_at":"2024-11-24T15:09:53.009Z","updated_at":"2025-10-29T22:38:32.213Z","avatar_url":"https://github.com/CatCodeGames.png","language":"C#","funding_links":[],"categories":[],"sub_categories":[],"readme":"# 1. Description\nThis repository contains a base class for creating singletons in Unity, along with auxiliary classes for flexible configuration and management of singletons. \nSupported modes include:\n- finding on the scene\n- creating a new object\n- loading from resources\nThe singleton is not recreated upon application shutdown or when exiting Play Mode to prevent errors.\n\n\n# 2. Class Descriptions\n### 1. ```MonoSingleton\u003cT\u003e```.\nThis is the base abstract class for all singleton classes.\n- ```static T Instance``` - a property that provides global access to the single instance of the singleton. Automatically creates the instance upon first access.\n- ```static bool Instance``` - a property that checks if the singleton instance currently exists.\n- ```static event Action\u003cT\u003e InstanceChanged``` - an event that is triggered when the singleton instance is created or destroyed.\n- ```virtual void OnInitialize()``` - a method called when the singleton instance is created, used for initialization.\n- ```virtual void OnDeinitialize()``` - a method called when the singleton instance is destroyed, used for deinitialization and resource cleanup.\n\n### 2. ```SingletonConfigAttribute```\nThe ```SingletonConfigAttribute``` is used to configure the creation and management modes of a singleton. It allows for controlling the creation process of singleton instances in Unity with various configuration parameters.\n- ```CreationMode``` - A mask controlling the instance creation mode. It can include finding the object on the scene, creating a new instance, or loading from resources.\n- ```HideFlags``` - mask that controls object destruction, saving and visibility in inspectors. Moredetails in the [Unity documentation](https://docs.unity3d.com/ScriptReference/HideFlags.html).\n- ```DontDestroyOnLoad``` - Indicates whether the object should be preserved when loading a new scene. More details in the [Unity documentation](https://docs.unity3d.com/ScriptReference/Object.DontDestroyOnLoad.html).\n- ```InstanceName``` - The name of the singleton instance in the Unity inspector.\n- ```ResourceName``` - The path to the resource, used if ```ObjectCreationMode.LoadFromResources``` is set.\n\n\n# 3. How to Use\n### 1. Create your class by inheriting from the base class ```MonoSingleton\u003cT\u003e```:\n- If necessary, override the ```OnInitialize``` and ```OnDeinitialize``` methods, which are called when the Singleton instance is created and destroyed.\n### 2. Apply the ```SingletonConfigAttribute``` to configure the creation and management mode:\n\n\n# 4. Example\n### Create Singlton.\n``` csharp\n    [ObjectCreationConfig(\n        creationMode: ObjectCreationMode.CreateNewInstance| ObjectCreationMode.LoadFromResources,\n        dontDestroyOnLoad: true,\n        hideFlags: HideFlags.None,\n        instanceName: nameof(ExampleSingleton),\n        resourceName: \"Singletons/\" + nameof(ExampleSingleton))]\n    public sealed class ExampleSingleton : MonoSingleton\u003cExampleSingleton\u003e\n    {        \n        public static void DoSomethingStatic()\n            =\u003e Instance?.DoSomething();\n\n        public void DoSomething()\n        {\n            ...\n        }\n    }\n```\n### Use Singlton\n``` csharp\n    ExampleSingleton.DoSomethingStatic();\n```\n\n\n# 1. Описание\nЭтот репозиторий содержит базовый класс для создания синглтонов в Unity, а также вспомогательные классы для гибкой настройки создания и управления синглтонами.\nПоддерживается следующие режимы: \n- поиск на сцене\n- создание нового объекта\n- загрузка из ресурсов\nСинглтон не создается повторно при завершении приложения или остановке Play Mode, чтобы избежать ошибок. \n\n\n# 2. Описание классов\n### 1. ```MonoSingleton\u003cT\u003e```.\n  Базовый абстрактный класс для всех классов синглтонов.\n- ```static T Instance``` - свойство, предоставляющее глобальный доступ к единственному экземпляру синглтона. При первом обращении автоматически создаёт его.\n- ```static bool Instance``` - свойство, проверябщее существует ли в данный момент экземпляр синглтона.  \n- ```static event Action\u003cT\u003e InstanceChanged``` - событие, вызываемое при создании или уничтожении экземпляра синглтона.\n- ```virtual void OnInitialize()``` - метод, вызываемый при создании экземпляра, служит для инициализации объекта.\n- ```virtual void OnDeinitialize()``` - метод, вызываемый при удалении экземпляра. предназначени для деинициализации и освобождения ресурсов, связаннх с объектом.\n\n### 2. ```SingletonConfigAttribute```\n  Атрибут ```SingletonConfigAttribute``` используется для настройки режима создания и управления синглтоном.\nПозволяет контролировать процесс создания экземпляров синглтона в Unity, предоставляя множество параметров для настройки.\n- ```CreationMode``` - маска, управляющая режимом создания экземпляра синглтона. Поиск на сцене, создание нового экземпляра или загрузка из ресурсов.\n- ```HideFlags``` - маска управляющая уничтожением, сохранением и видимостью объекта в инспекторе. Подробности в [документации Unity](https://docs.unity3d.com/ScriptReference/HideFlags.html)\n- ```DontDestroyOnLoad``` - сохранять ли объект при загрузке новой сцены. Подробности в [документации Unity](https://docs.unity3d.com/ScriptReference/Object.DontDestroyOnLoad.html)\n- ```InstanceName``` - имя экземпляра синглтона в инспекторе Unity.\n- ```ResourceName``` - путь к ресурсу, если используется ```ObjectCreationMode.LoadFromResources```.\n\n\n# 3. Как использовать.\n### 1. Создайте свой класс, унаследовав его от базового класса ```MonoSingleton\u003cT\u003e```\n- При необходимости переопределите методы ```OnInitialize``` и ```OnDeinitialize```, вызываемые при создании и уничтожении экземпляра синглтон.\n### 2. Примените атрибут SingletonConfigAttribute для настройки режима создания и управления.\n\n\n# 4. Пример\nСоздание синглтона.\n``` csharp\n    [ObjectCreationConfig(\n        creationMode: ObjectCreationMode.CreateNewInstance| ObjectCreationMode.LoadFromResources,\n        dontDestroyOnLoad: true,\n        hideFlags: HideFlags.None,\n        instanceName: nameof(ExampleSingleton),\n        resourceName: \"Singletons/\" + nameof(ExampleSingleton))]\n    public sealed class ExampleSingleton : MonoSingleton\u003cExampleSingleton\u003e\n    {        \n        public static void DoSomethingStatic()\n            =\u003e Instance?.DoSomething();\n\n        public void DoSomething()\n        {\n            ...\n        }\n    }\n```\n\nИспользование синглтона\n``` csharp\n    ExampleSingleton.DoSomethingStatic();\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcatcodegames%2Fsingleton","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fcatcodegames%2Fsingleton","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcatcodegames%2Fsingleton/lists"}