├── .gitignore ├── img ├── 1.jpg ├── 2.jpg ├── 1.jpg.meta └── 2.jpg.meta ├── src ├── Extensions.cs.meta ├── BaseConverter.cs.meta ├── EcsConverter.cs.meta ├── ComponentConverter.cs.meta ├── ComponentsContainer.cs.meta ├── BaseConverter.cs ├── ComponentsContainer.cs ├── ComponentConverter.cs ├── Extensions.cs └── EcsConverter.cs ├── README.md.meta ├── README_en.md.meta ├── package.json.meta ├── LICENSE_en.md.meta ├── LICENSE_ru.md.meta ├── img.meta ├── src.meta ├── LeoEcsLiteEntityConverter.asmdef.meta ├── package.json ├── LeoEcsLiteEntityConverter.asmdef ├── LICENSE_en.md ├── LICENSE_ru.md ├── README.md └── README_en.md /.gitignore: -------------------------------------------------------------------------------- 1 | *.sln 2 | .vscode 3 | .idea 4 | .DS_Store 5 | bin 6 | obj 7 | Library 8 | Temp -------------------------------------------------------------------------------- /img/1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AndreyBirchenko/LeoEcsLiteEntityConverter/HEAD/img/1.jpg -------------------------------------------------------------------------------- /img/2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AndreyBirchenko/LeoEcsLiteEntityConverter/HEAD/img/2.jpg -------------------------------------------------------------------------------- /src/Extensions.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 3ba99728afd84bb4ae442063f3b21c82 3 | timeCreated: 1665929275 -------------------------------------------------------------------------------- /src/BaseConverter.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 3958a9db96b6427cb4ec92d8366dbdc8 3 | timeCreated: 1665927895 -------------------------------------------------------------------------------- /src/EcsConverter.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 54ebeb053e9c4413b4bea422ed07eeb5 3 | timeCreated: 1679588959 -------------------------------------------------------------------------------- /src/ComponentConverter.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 07e4d1e5fd6f49ccb3c857d476b52b83 3 | timeCreated: 1665926132 -------------------------------------------------------------------------------- /src/ComponentsContainer.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 09d40b90da6b42589971320ba7a7bc95 3 | timeCreated: 1665928323 -------------------------------------------------------------------------------- /README.md.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 6447b091468a3d944a5c76b4794f3ffe 3 | TextScriptImporter: 4 | externalObjects: {} 5 | userData: 6 | assetBundleName: 7 | assetBundleVariant: 8 | -------------------------------------------------------------------------------- /README_en.md.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 62a11f1efbb5e694d942bc1c1da1bb40 3 | TextScriptImporter: 4 | externalObjects: {} 5 | userData: 6 | assetBundleName: 7 | assetBundleVariant: 8 | -------------------------------------------------------------------------------- /package.json.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 52c2c6ca2a945ca4ea117b289f57f0df 3 | TextScriptImporter: 4 | externalObjects: {} 5 | userData: 6 | assetBundleName: 7 | assetBundleVariant: 8 | -------------------------------------------------------------------------------- /LICENSE_en.md.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: b5c7f50153206ca41899439f4dbc5047 3 | TextScriptImporter: 4 | externalObjects: {} 5 | userData: 6 | assetBundleName: 7 | assetBundleVariant: 8 | -------------------------------------------------------------------------------- /LICENSE_ru.md.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 2b7ae897c03aff744b3dff25ab691ddf 3 | TextScriptImporter: 4 | externalObjects: {} 5 | userData: 6 | assetBundleName: 7 | assetBundleVariant: 8 | -------------------------------------------------------------------------------- /img.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 7ddb0b8b263d7344db6180edb0d6cff7 3 | folderAsset: yes 4 | DefaultImporter: 5 | externalObjects: {} 6 | userData: 7 | assetBundleName: 8 | assetBundleVariant: 9 | -------------------------------------------------------------------------------- /src.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 58bd9c07bfd81414ab0ac3b27553d234 3 | folderAsset: yes 4 | DefaultImporter: 5 | externalObjects: {} 6 | userData: 7 | assetBundleName: 8 | assetBundleVariant: 9 | -------------------------------------------------------------------------------- /LeoEcsLiteEntityConverter.asmdef.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 6edd76a60c59af6479735feb61d29472 3 | AssemblyDefinitionImporter: 4 | externalObjects: {} 5 | userData: 6 | assetBundleName: 7 | assetBundleVariant: 8 | -------------------------------------------------------------------------------- /src/BaseConverter.cs: -------------------------------------------------------------------------------- 1 | using Leopotam.EcsLite; 2 | 3 | using UnityEngine; 4 | 5 | namespace AB_Utility.FromSceneToEntityConverter 6 | { 7 | [RequireComponent(typeof(ComponentsContainer))] 8 | public abstract class BaseConverter : MonoBehaviour 9 | { 10 | public abstract void Convert(EcsPackedEntityWithWorld entityWithWorld); 11 | } 12 | } -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "com.anbi.leoecslite.entityconverter", 3 | "author": "AndreyBirchenko", 4 | "version": "1.0.1", 5 | "displayName": "Leo Ecs Lite Entity Converter", 6 | "description": "Leo Ecs Lite Entity Converter", 7 | "unity": "2020.3", 8 | "keywords": [], 9 | "repository": { 10 | "type": "git", 11 | "url": "https://github.com/AndreyBirchenko/LeoEcsLiteEntityConverter.git" 12 | } 13 | } -------------------------------------------------------------------------------- /LeoEcsLiteEntityConverter.asmdef: -------------------------------------------------------------------------------- 1 | { 2 | "name": "LeoEcsLiteEntityConverter", 3 | "rootNamespace": "", 4 | "references": [ 5 | "GUID:e59bf9fc7d5a44b18a819a92edd46163" 6 | ], 7 | "includePlatforms": [], 8 | "excludePlatforms": [], 9 | "allowUnsafeCode": false, 10 | "overrideReferences": false, 11 | "precompiledReferences": [], 12 | "autoReferenced": true, 13 | "defineConstraints": [], 14 | "versionDefines": [], 15 | "noEngineReferences": false 16 | } -------------------------------------------------------------------------------- /src/ComponentsContainer.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | using UnityEngine; 4 | 5 | namespace AB_Utility.FromSceneToEntityConverter 6 | { 7 | [DisallowMultipleComponent] 8 | public class ComponentsContainer : MonoBehaviour 9 | { 10 | [SerializeField] private BaseConverter[] _converters; 11 | [SerializeField] private bool _destroyAfterConversion; 12 | public BaseConverter[] Converters => _converters; 13 | public bool DestroyAfterConversion => _destroyAfterConversion; 14 | 15 | internal void GetConverters() 16 | { 17 | _converters = GetComponents(); 18 | } 19 | } 20 | } -------------------------------------------------------------------------------- /src/ComponentConverter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | using Leopotam.EcsLite; 4 | 5 | using UnityEngine; 6 | 7 | namespace AB_Utility.FromSceneToEntityConverter 8 | { 9 | [DisallowMultipleComponent] 10 | public class ComponentConverter : BaseConverter where T : struct 11 | { 12 | [SerializeField] protected T _component; 13 | 14 | public override void Convert(EcsPackedEntityWithWorld entityWithWorld) 15 | { 16 | if (entityWithWorld.Unpack(out var world, out var entity)) 17 | { 18 | ref var component = ref world.GetPool().Add(entity); 19 | component = _component; 20 | } 21 | } 22 | 23 | private void Reset() 24 | { 25 | var container = GetComponent(); 26 | container.GetConverters(); 27 | } 28 | } 29 | } -------------------------------------------------------------------------------- /LICENSE_en.md: -------------------------------------------------------------------------------- 1 | Copyright (c) 2023 andrey_birchenko@mail.ru 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------------- /LICENSE_ru.md: -------------------------------------------------------------------------------- 1 | Copyright (c) 2023 andrey_birchenko@mail.ru 2 | 3 | Данная лицензия разрешает лицам, получившим копию данного программного обеспечения и сопутствующей документации (в дальнейшем именуемыми «Программное обеспечение»), безвозмездно использовать Программное обеспечение без ограничений, включая неограниченное право на использование, копирование, изменение, слияние, публикацию, распространение, сублицензирование и/или продажу копий Программного обеспечения, а также лицам, которым предоставляется данное Программное обеспечение, при соблюдении следующих условий: 4 | 5 | Указанное выше уведомление об авторском праве и данные условия должны быть включены во все копии или значимые части данного Программного обеспечения. 6 | 7 | ДАННОЕ ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ ПРЕДОСТАВЛЯЕТСЯ «КАК ЕСТЬ», БЕЗ КАКИХ-ЛИБО ГАРАНТИЙ, ЯВНО ВЫРАЖЕННЫХ ИЛИ ПОДРАЗУМЕВАЕМЫХ, ВКЛЮЧАЯ ГАРАНТИИ ТОВАРНОЙ ПРИГОДНОСТИ, СООТВЕТСТВИЯ ПО ЕГО КОНКРЕТНОМУ НАЗНАЧЕНИЮ И ОТСУТСТВИЯ НАРУШЕНИЙ, НО НЕ ОГРАНИЧИВАЯСЬ ИМИ. НИ В КАКОМ СЛУЧАЕ АВТОРЫ ИЛИ ПРАВООБЛАДАТЕЛИ НЕ НЕСУТ ОТВЕТСТВЕННОСТИ ПО КАКИМ-ЛИБО ИСКАМ, ЗА УЩЕРБ ИЛИ ПО ИНЫМ ТРЕБОВАНИЯМ, В ТОМ ЧИСЛЕ, ПРИ ДЕЙСТВИИ КОНТРАКТА, ДЕЛИКТЕ ИЛИ ИНОЙ СИТУАЦИИ, ВОЗНИКШИМ ИЗ-ЗА ИСПОЛЬЗОВАНИЯ ПРОГРАММНОГО ОБЕСПЕЧЕНИЯ ИЛИ ИНЫХ ДЕЙСТВИЙ С ПРОГРАММНЫМ ОБЕСПЕЧЕНИЕМ. -------------------------------------------------------------------------------- /src/Extensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | using Leopotam.EcsLite; 5 | 6 | using UnityEngine; 7 | 8 | using Object = UnityEngine.Object; 9 | 10 | namespace AB_Utility.FromSceneToEntityConverter 11 | { 12 | public static class Extensions 13 | { 14 | private static HashSet _dirtyWorlds = new HashSet(); 15 | 16 | public static IEcsSystems ConvertScene(this IEcsSystems systems) 17 | { 18 | var world = systems.GetWorld(); 19 | #if DEBUG 20 | if (_dirtyWorlds.Contains(world)) 21 | { 22 | throw new Exception( 23 | "You cannot convert systems with the same world twice more info"); 24 | } 25 | 26 | _dirtyWorlds.Add(world); 27 | #endif 28 | var containers = UnityEngine.Object.FindObjectsOfType(true); 29 | 30 | for (int i = 0; i < containers.Length; i++) 31 | { 32 | var container = containers[i]; 33 | EcsConverter.ConvertContainer(container, world); 34 | } 35 | 36 | return systems; 37 | } 38 | } 39 | } -------------------------------------------------------------------------------- /img/1.jpg.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 51271cc5319b60342925c77466af8ddb 3 | TextureImporter: 4 | internalIDToNameTable: [] 5 | externalObjects: {} 6 | serializedVersion: 11 7 | mipmaps: 8 | mipMapMode: 0 9 | enableMipMap: 0 10 | sRGBTexture: 1 11 | linearTexture: 0 12 | fadeOut: 0 13 | borderMipMap: 0 14 | mipMapsPreserveCoverage: 0 15 | alphaTestReferenceValue: 0.5 16 | mipMapFadeDistanceStart: 1 17 | mipMapFadeDistanceEnd: 3 18 | bumpmap: 19 | convertToNormalMap: 0 20 | externalNormalMap: 0 21 | heightScale: 0.25 22 | normalMapFilter: 0 23 | isReadable: 0 24 | streamingMipmaps: 0 25 | streamingMipmapsPriority: 0 26 | vTOnly: 0 27 | ignoreMasterTextureLimit: 0 28 | grayScaleToAlpha: 0 29 | generateCubemap: 6 30 | cubemapConvolution: 0 31 | seamlessCubemap: 0 32 | textureFormat: 1 33 | maxTextureSize: 2048 34 | textureSettings: 35 | serializedVersion: 2 36 | filterMode: 1 37 | aniso: 1 38 | mipBias: 0 39 | wrapU: 1 40 | wrapV: 1 41 | wrapW: 1 42 | nPOTScale: 0 43 | lightmap: 0 44 | compressionQuality: 50 45 | spriteMode: 1 46 | spriteExtrude: 1 47 | spriteMeshType: 1 48 | alignment: 0 49 | spritePivot: {x: 0.5, y: 0.5} 50 | spritePixelsToUnits: 100 51 | spriteBorder: {x: 0, y: 0, z: 0, w: 0} 52 | spriteGenerateFallbackPhysicsShape: 1 53 | alphaUsage: 1 54 | alphaIsTransparency: 1 55 | spriteTessellationDetail: -1 56 | textureType: 8 57 | textureShape: 1 58 | singleChannelComponent: 0 59 | flipbookRows: 1 60 | flipbookColumns: 1 61 | maxTextureSizeSet: 0 62 | compressionQualitySet: 0 63 | textureFormatSet: 0 64 | ignorePngGamma: 0 65 | applyGammaDecoding: 0 66 | platformSettings: 67 | - serializedVersion: 3 68 | buildTarget: DefaultTexturePlatform 69 | maxTextureSize: 2048 70 | resizeAlgorithm: 0 71 | textureFormat: -1 72 | textureCompression: 1 73 | compressionQuality: 50 74 | crunchedCompression: 0 75 | allowsAlphaSplitting: 0 76 | overridden: 0 77 | androidETC2FallbackOverride: 0 78 | forceMaximumCompressionQuality_BC6H_BC7: 0 79 | spriteSheet: 80 | serializedVersion: 2 81 | sprites: [] 82 | outline: [] 83 | physicsShape: [] 84 | bones: [] 85 | spriteID: 5e97eb03825dee720800000000000000 86 | internalID: 0 87 | vertices: [] 88 | indices: 89 | edges: [] 90 | weights: [] 91 | secondaryTextures: [] 92 | nameFileIdTable: {} 93 | spritePackingTag: 94 | pSDRemoveMatte: 0 95 | pSDShowRemoveMatteOption: 0 96 | userData: 97 | assetBundleName: 98 | assetBundleVariant: 99 | -------------------------------------------------------------------------------- /img/2.jpg.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: b526daad9ea23344b89a7ae7dc0f7c34 3 | TextureImporter: 4 | internalIDToNameTable: [] 5 | externalObjects: {} 6 | serializedVersion: 11 7 | mipmaps: 8 | mipMapMode: 0 9 | enableMipMap: 0 10 | sRGBTexture: 1 11 | linearTexture: 0 12 | fadeOut: 0 13 | borderMipMap: 0 14 | mipMapsPreserveCoverage: 0 15 | alphaTestReferenceValue: 0.5 16 | mipMapFadeDistanceStart: 1 17 | mipMapFadeDistanceEnd: 3 18 | bumpmap: 19 | convertToNormalMap: 0 20 | externalNormalMap: 0 21 | heightScale: 0.25 22 | normalMapFilter: 0 23 | isReadable: 0 24 | streamingMipmaps: 0 25 | streamingMipmapsPriority: 0 26 | vTOnly: 0 27 | ignoreMasterTextureLimit: 0 28 | grayScaleToAlpha: 0 29 | generateCubemap: 6 30 | cubemapConvolution: 0 31 | seamlessCubemap: 0 32 | textureFormat: 1 33 | maxTextureSize: 2048 34 | textureSettings: 35 | serializedVersion: 2 36 | filterMode: 1 37 | aniso: 1 38 | mipBias: 0 39 | wrapU: 1 40 | wrapV: 1 41 | wrapW: 1 42 | nPOTScale: 0 43 | lightmap: 0 44 | compressionQuality: 50 45 | spriteMode: 1 46 | spriteExtrude: 1 47 | spriteMeshType: 1 48 | alignment: 0 49 | spritePivot: {x: 0.5, y: 0.5} 50 | spritePixelsToUnits: 100 51 | spriteBorder: {x: 0, y: 0, z: 0, w: 0} 52 | spriteGenerateFallbackPhysicsShape: 1 53 | alphaUsage: 1 54 | alphaIsTransparency: 1 55 | spriteTessellationDetail: -1 56 | textureType: 8 57 | textureShape: 1 58 | singleChannelComponent: 0 59 | flipbookRows: 1 60 | flipbookColumns: 1 61 | maxTextureSizeSet: 0 62 | compressionQualitySet: 0 63 | textureFormatSet: 0 64 | ignorePngGamma: 0 65 | applyGammaDecoding: 0 66 | platformSettings: 67 | - serializedVersion: 3 68 | buildTarget: DefaultTexturePlatform 69 | maxTextureSize: 2048 70 | resizeAlgorithm: 0 71 | textureFormat: -1 72 | textureCompression: 1 73 | compressionQuality: 50 74 | crunchedCompression: 0 75 | allowsAlphaSplitting: 0 76 | overridden: 0 77 | androidETC2FallbackOverride: 0 78 | forceMaximumCompressionQuality_BC6H_BC7: 0 79 | spriteSheet: 80 | serializedVersion: 2 81 | sprites: [] 82 | outline: [] 83 | physicsShape: [] 84 | bones: [] 85 | spriteID: 5e97eb03825dee720800000000000000 86 | internalID: 0 87 | vertices: [] 88 | indices: 89 | edges: [] 90 | weights: [] 91 | secondaryTextures: [] 92 | nameFileIdTable: {} 93 | spritePackingTag: 94 | pSDRemoveMatte: 0 95 | pSDShowRemoveMatteOption: 0 96 | userData: 97 | assetBundleName: 98 | assetBundleVariant: 99 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # LeoEcsLite Entity Converter 2 | *Read this in other languages: [Русский](https://github.com/AndreyBirchenko/LeoEcsLiteEntityConverter/blob/master/README.md), [English](https://github.com/AndreyBirchenko/LeoEcsLiteEntityConverter/blob/master/README_en.md)* 3 | 4 | Обеспечивает автоматическое создание сущностей с компонентами через инспектор. 5 | 6 | > Проверено на Unity 2020.3 и содержит asmdef-описания для компиляции в виде отдельных сборок и уменьшения времени рекомпиляции основного проекта. 7 | 8 | Для обратной связи https://t.me/AndreyBirchenko 9 | 10 | # Установка 11 | **Внимание!** Для работы этого расширения сначала установите [LeoEcsLite](https://github.com/Leopotam/ecslite) 12 | 13 | ## В виде unity модуля 14 | Поддерживается установка в виде unity-модуля через git-ссылку в PackageManager или прямое редактирование `Packages/manifest.json`: 15 | ``` 16 | "com.anbi.leoecslite.entityconverter": "https://github.com/AndreyBirchenko/LeoEcsLiteEntityConverter.git", 17 | ``` 18 | 19 | # Интеграция 20 | ```c# 21 | var systems = new EcsSystems (new EcsWorld ()); 22 | systems 23 | .Add (new System1 ()) 24 | .AddWorld (new EcsWorld (), "events") 25 | // ... 26 | .ConvertScene() 27 | .Init (); 28 | ``` 29 | 30 | # Использование 31 | 32 | Чтобы добавить компонент на гейм объект сначала создайте класс конвертер и унаследуйте его от `ComponentConverter` 33 | 34 | **ВАЖНО:** У компонента должен быть атрибут `[Serializable]` если вы хотите чтобы его поля отображались в инспекторе. 35 | ```c# 36 | [Serializable] 37 | public struct TestComponent 38 | { 39 | public int Value; 40 | } 41 | 42 | public class TestComponentConverter : ComponentConverter 43 | { 44 | } 45 | ``` 46 | 47 | После этого вы сможете добавить компонент на гейм объект через кнопку **AddComponent** 48 | 49 | ![alt text](https://github.com/AndreyBirchenko/LeoEcsLiteEntityConverter/blob/master/img/1.jpg) 50 | 51 | Вместе с вашим конвертером автоматически добавится ещё и `ComponentsContainer` он нужен для конвертации. 52 | 53 | Если вы хотите чтобы после конвертации все ненужные компоненты удалились с гейм объекта поставьте галочку `DestroyAfterConversion` 54 | 55 | Теперь когда вы запустите проект будет автоматически создана сущность с компонентом `TestComponent` и значением `Value` из инспектора 56 | 57 | ![alt text](https://github.com/AndreyBirchenko/LeoEcsLiteEntityConverter/blob/master/img/2.jpg) 58 | 59 | # Конвертация по ходу исполнения программы 60 | Вы можете конвертировать объекты при создании 61 | ```c# 62 | var objectView = EcsConverter.InstantiateAndCreateEntity(ObjectPrefab, _ecsWorld); 63 | ``` 64 | Для этого на префабе который вы собираетесь конвертировать должен быть `ComponentsContainer` 65 | # 66 | -------------------------------------------------------------------------------- /README_en.md: -------------------------------------------------------------------------------- 1 | # LeoEcsLite Entity Converter 2 | *Read this in other languages: [Русский](https://github.com/AndreyBirchenko/LeoEcsLiteEntityConverter/blob/master/README.md), [English](https://github.com/AndreyBirchenko/LeoEcsLiteEntityConverter/blob/master/README_en.md)* 3 | 4 | Provides automatic creation of entities with components through the inspector. 5 | 6 | > Tested on Unity 2020.3 and contains asmdef descriptions for compilation in the form of separate assemblies and reducing the recompilation time of the main project. 7 | > 8 | > For feedback https://t.me/AndreyBirchenko 9 | 10 | # Installation 11 | **Attention!** For this extension to work, first install [LeoEcsLite](https://github.com/Leopotam/ecslite) 12 | 13 | ## As a unity module 14 | Installation as a unity module via a git link in PackageManager or direct editing of `Packages/manifest.json`: 15 | ``` 16 | "com.anbi.leoecslite.entityconverter": "https://github.com/AndreyBirchenko/LeoEcsLiteEntityConverter.git", 17 | ``` 18 | 19 | # Integration 20 | ```c# 21 | var systems = new EcsSystems (new EcsWorld ()); 22 | systems 23 | .Add (new System1 ()) 24 | .AddWorld (new EcsWorld (), "events") 25 | // ... 26 | .ConvertScene() 27 | .Init (); 28 | ``` 29 | 30 | # Usage 31 | 32 | To add a component to a game object, first create a converter class and inherit it from `ComponentConverter` 33 | 34 | **IMPORTANT:** The component must have the attribute `[Serializable]` if you want its fields to be displayed in the inspector. 35 | ```c# 36 | [Serializable] 37 | public struct TestComponent 38 | { 39 | public int Value; 40 | } 41 | 42 | public class TestComponentConverter : ComponentConverter 43 | { 44 | } 45 | ``` 46 | 47 | After that, you can add the component to the game object via the **AddComponent button** 48 | 49 | ![alt text](https://github.com/AndreyBirchenko/LeoEcsLiteEntityConverter/blob/master/img/1.jpg) 50 | 51 | Along with your converter, a `ComponentsContainer` will be added automatically. It is needed for conversion. 52 | 53 | If you want all unnecessary components to be removed from the game object after conversion, check the box `DestroyAfterConversion` 54 | 55 | Now when you start the project, an entity with the `TestComponent` component and the `Value` value from the inspector will be automatically created 56 | 57 | ![alt text](https://github.com/AndreyBirchenko/LeoEcsLiteEntityConverter/blob/master/img/2.jpg) 58 | # Conversion during the execution of the program 59 | You can convert objects when instantiating 60 | ```c# 61 | var object View = Epsconverter.Instantiate And Create Entity(Object Prefab, _eco World); 62 | ``` 63 | To do this, the prefab that you are going to convert must have a `ComponentsContainer` 64 | # 65 | -------------------------------------------------------------------------------- /src/EcsConverter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | using Leopotam.EcsLite; 4 | 5 | using UnityEngine; 6 | 7 | using Object = UnityEngine.Object; 8 | 9 | namespace AB_Utility.FromSceneToEntityConverter 10 | { 11 | public static class EcsConverter 12 | { 13 | public static T InstantiateAndCreateEntity 14 | (T original, Vector3 position, Quaternion rotation, Transform parent, 15 | EcsWorld world) 16 | where T : UnityEngine.Object 17 | { 18 | var obj = Object.Instantiate(original, position, rotation, parent); 19 | ConvertObject(obj as GameObject, world); 20 | return obj; 21 | } 22 | 23 | public static T InstantiateAndCreateEntity 24 | (T original, Vector3 position, Quaternion rotation, EcsWorld world) 25 | where T : UnityEngine.Object 26 | { 27 | var obj = Object.Instantiate(original, position, rotation); 28 | ConvertObject(obj as GameObject, world); 29 | return obj; 30 | } 31 | 32 | public static T InstantiateAndCreateEntity 33 | (T original, Transform parent, EcsWorld world, bool worldPositionStay) 34 | where T : UnityEngine.Object 35 | { 36 | var obj = Object.Instantiate(original, parent, worldPositionStay); 37 | ConvertObject(obj as GameObject, world); 38 | return obj; 39 | } 40 | 41 | public static T InstantiateAndCreateEntity 42 | (T original, Transform parent, EcsWorld world) 43 | where T : UnityEngine.Object 44 | { 45 | var obj = Object.Instantiate(original, parent); 46 | ConvertObject(obj as GameObject, world); 47 | return obj; 48 | } 49 | 50 | public static T InstantiateAndCreateEntity 51 | (T original, EcsWorld world) 52 | where T : UnityEngine.Object 53 | { 54 | var obj = Object.Instantiate(original); 55 | ConvertObject(obj as GameObject, world); 56 | return obj; 57 | } 58 | 59 | public static void ConvertContainer(ComponentsContainer container, EcsWorld world) 60 | { 61 | var destroyAfterConversion = container.DestroyAfterConversion; 62 | var entity = world.NewEntity(); 63 | var packedEntity = world.PackEntityWithWorld(entity); 64 | 65 | for (int j = 0; j < container.Converters.Length; j++) 66 | { 67 | var converter = container.Converters[j]; 68 | converter.Convert(packedEntity); 69 | 70 | if (destroyAfterConversion) 71 | { 72 | UnityEngine.Object.Destroy(converter); 73 | } 74 | } 75 | 76 | if (destroyAfterConversion) 77 | { 78 | UnityEngine.Object.Destroy(container); 79 | } 80 | } 81 | 82 | public static void ConvertObject(GameObject obj, EcsWorld world) 83 | { 84 | var container = obj.GetComponent(); 85 | #if DEBUG 86 | if (!container) 87 | { 88 | throw new Exception("You can not instantiate and create entity without components container"); 89 | } 90 | #endif 91 | 92 | ConvertContainer(container, world); 93 | } 94 | } 95 | } --------------------------------------------------------------------------------