Exemplo n.º 1
0
        public void Systems_OnlySystemsFromListAndGameObjectConversionSystemAreAdded()
        {
            using (var world = new World("test world"))
            {
                var settings = new GameObjectConversionSettings
                {
                    DestinationWorld    = world,
                    SceneGUID           = new Hash128(1, 2, 3, 4),
                    DebugConversionName = "test name",
                    ConversionFlags     = GameObjectConversionUtility.ConversionFlags.AddEntityGUID,
#if UNITY_EDITOR
                    BuildConfiguration = BuildConfiguration.CreateInstance(),
#endif
                    Systems = new List <Type> {
                        typeof(TestConversionSystem)
                    },
                    NamespaceID               = 123,
                    ConversionWorldCreated    = _ => {},
                    ConversionWorldPreDispose = _ => {},
                };
                using (var conversionWorld = settings.CreateConversionWorld())
                {
                    foreach (var system in conversionWorld.Systems)
                    {
                        if (system is ComponentSystemGroup || system == null)
                        {
                            continue;
                        }
                        Assert.That(system is TestConversionSystem || system is GameObjectConversionMappingSystem, $"System is of unexpected type {system.GetType()}");
                    }
                }
            }
        }
        public new void Setup()
        {
            m_DstWorld = new World(TestContext.CurrentContext.Test.FullName);
            var settings = new GameObjectConversionSettings(m_DstWorld, ConversionFlags.AssignName | ConversionFlags.AddEntityGUID);

            m_MappingSystem = World.AddSystem(new GameObjectConversionMappingSystem(settings));
        }
Exemplo n.º 3
0
    // Start is called before the first frame update
    void Start()
    {
        manager = World.DefaultGameObjectInjectionWorld.EntityManager;
        var settings = GameObjectConversionSettings.FromWorld(World.DefaultGameObjectInjectionWorld, null);
        var prefab   = GameObjectConversionUtility.ConvertGameObjectHierarchy(tankPrefab, settings);

        for (int i = 0; i < numTanks; i++)
        {
            var   instance = manager.Instantiate(prefab);
            float x        = UnityEngine.Random.Range(-100, 100);
            float z        = UnityEngine.Random.Range(-100, 100);
            var   position = transform.TransformPoint(new float3(x, 0, z));
            manager.SetComponentData(instance, new Translation {
                Value = position
            });

            var q = Quaternion.Euler(new Vector3(0, 45, 0));
            manager.SetComponentData(instance, new Rotation {
                Value = new quaternion(q.x, q.y, q.z, q.w)
            });

            manager.SetComponentData(instance, new TankData {
                speed         = UnityEngine.Random.Range(2, 8),
                rotationSpeed = UnityEngine.Random.Range(1, 10),
                currentWP     = 0
            });
        }
    }
Exemplo n.º 4
0
    private void Awake()
    {
        // 如果当前main不等于空并且不为当前对象,就直接返回
        // 防止重复的对象定义
        if (main != null && main != this)
        {
            Destroy(gameObject);
            return;
        }

        main         = this;
        playerScores = new int[2];

        // 获取默认世界的对象管理器
        manager = World.DefaultGameObjectInjectionWorld.EntityManager;

        //获取默认世界的配置,并且初始化对象ballPrefab到场景世界中
        GameObjectConversionSettings settings = GameObjectConversionSettings.FromWorld(World.DefaultGameObjectInjectionWorld, null);

        ballEntityPrefab = GameObjectConversionUtility.ConvertGameObjectHierarchy(ballPrefab, settings); // 由于这里本身没有

        oneSecond = new WaitForSeconds(1f);                                                              // 定义常量,一秒的等待时间
        delay     = new WaitForSeconds(respawnDelay);                                                    //获取和定义复位时间

        StartCoroutine(CountdownAndSpawnBall());                                                         // 开始协程
    }
Exemplo n.º 5
0
        public void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem)
        {
            dstManager.AddComponent <Spline2DBenchmarkData>(entity);

            // convert prefab to entity
            World defaultWorld = World.DefaultGameObjectInjectionWorld;
            GameObjectConversionSettings settings = GameObjectConversionSettings.FromWorld(defaultWorld, null);
            Entity converted = GameObjectConversionUtility.ConvertGameObjectHierarchy(Prefab, settings);

            dstManager.SetComponentData(entity, new Spline2DBenchmarkData
            {
                Quantity = Quantity,
                Prefab   = converted
            });

            if (BezierSpline != null)
            {
                if (!BezierSpline.SplineVarianceEntityData.HasValue)
                {
                    BezierSpline.Convert(dstManager.CreateEntity(), dstManager, conversionSystem);
                }

                dstManager.AddSharedComponentData(entity, BezierSpline.SplineVarianceEntityData.Value);
            }
        }
        public void ConvertGameObject_HasOnlyTransform_ProducesEntityWithPositionAndRotation()
        {
            var scene = SceneManager.GetActiveScene();
            var go    = CreateGameObject("Test Conversion");

            go.transform.localPosition = new Vector3(1, 2, 3);

            using (var blobAssetStore = new BlobAssetStore())
            {
                var settings = GameObjectConversionSettings.FromWorld(World, blobAssetStore);
                GameObjectConversionUtility.ConvertScene(scene, settings);

                EntitiesAssert.ContainsOnly(m_Manager,
                                            EntityMatch.Exact(
                                                new Translation {
                    Value = new float3(1, 2, 3)
                },
                                                new Rotation {
                    Value = quaternion.identity
                },
                                                new LocalToWorld {
                    Value = go.transform.localToWorldMatrix
                }));
            }
        }
Exemplo n.º 7
0
        private void Awake()
        {
            // Fetch World Settings, create entity prefab and fetch entityManager
            var settings      = GameObjectConversionSettings.FromWorld(World.DefaultGameObjectInjectionWorld, null);
            var prefab        = GameObjectConversionUtility.ConvertGameObjectHierarchy(_planePrefab, settings);
            var entityManager = World.DefaultGameObjectInjectionWorld.EntityManager;

            // Create the new Fading Plane based on the prefab provided
            var entity = entityManager.Instantiate(prefab);

            // add the cameraFadeParameters component to the newly created entity, and inject the parameters provided in the inspector
            entityManager.AddComponentData(entity, new CameraFadeParameters()
            {
                FadingSpeed            = _fadingSpeed,
                ShouldImmediatlyFadeIn = false,
                OldFadingSpeedFactor   = _fadingSpeed
            });

            // Check if the user want a fade in on start
            CheckFadeInOnSetupVRReady();

            if (_destroyEntityOnSceneUnloaded)
            {
                OnSceneUnloadedEntityDestroyer.CheckDestroyOnSceneUnload(ref entityManager, ref entity, gameObject.scene.buildIndex, "CameraFadeAuthoring");
            }

#if UNITY_EDITOR
            // Set it's name in Editor Mode for the Entity Debugger Window
            entityManager.SetName(entity, "Camera Fade Entity");
#endif

            Destroy(gameObject);


            /// <summary>
            /// Check if we want to fade in when setupVR is ready. Set the material alpha accordingly, and add a CameraFadeOnStart
            /// component to the entity to activate the CameraFadeOnSetupVRReadySystem
            /// </summary>
            void CheckFadeInOnSetupVRReady()
            {
                // Reset material color alpha based on whether we want to fade in or not when SetupVR is ready
                var newColor = _fadeMaterial.color;

                if (FadeInOnSetupVRReady)
                {
                    newColor.a = 1.0f;
                    entityManager.AddComponentData(entity, new CameraFadeOnStart()
                    {
                        TimeBeforeFadeIn     = TimeBeforeFirstFadeIn,
                        TimeSinceSceneLoaded = 0.0f
                    });
                }
                else
                {
                    newColor.a = 0.0f;
                }

                _fadeMaterial.color = newColor;
            }
        }
Exemplo n.º 8
0
    // Start is called before the first frame update
    void Start()
    {
        var settings      = GameObjectConversionSettings.FromWorld(World.DefaultGameObjectInjectionWorld, new BlobAssetStore());
        var prefab        = GameObjectConversionUtility.ConvertGameObjectHierarchy(Prefab, settings);
        var entityManager = World.DefaultGameObjectInjectionWorld.EntityManager;

        for (int slice = -radius; slice < radius; slice++)
        {
            for (int row = -radius; row < radius; row++)
            {
                for (int col = -radius; col < radius; col++)
                {
                    var instance = entityManager.Instantiate(prefab);

                    // Place the instantiated entity in a grid with some noise
                    var position = transform.TransformPoint(row * 2, slice * 2, col * 2);
                    entityManager.SetComponentData(instance, new LocalToWorld());
                    entityManager.SetComponentData(instance, new Translation {
                        Value = position
                    });
                    entityManager.SetComponentData(instance, new Flow {
                        Value = 0
                    });
                }
            }
        }
    }
Exemplo n.º 9
0
        private void ConvertPrefabs()
        {
            var settings = GameObjectConversionSettings.FromWorld(World.DefaultGameObjectInjectionWorld, null);

            _ballEntityPrefabs          = CreateEntityPrefabs(_ballPrefabs, settings);
            _gravitySwitchEntityPrefabs = CreateEntityPrefabs(_gravitySwitchPrefabs, settings);
        }
        public void ConvertGameObject_WithFilteredBuildSettings_ConversionDoesntRun()
        {
            var scene = SceneManager.GetActiveScene();
            var go    = CreateGameObject("Test Conversion");

            go.transform.localPosition = new Vector3(1, 2, 3);

            var bs = ScriptableObject.CreateInstance <BuildSettings>();

            bs.hideFlags = HideFlags.HideAndDontSave;

            bs.SetComponent(new ConversionSystemFilterSettings("Unity.Transforms.Hybrid"));

            var settings = new GameObjectConversionSettings
            {
                DestinationWorld = World,
                BuildSettings    = bs
            };

            GameObjectConversionUtility.ConvertScene(scene, settings);

            // We still expect to find an Entity, just with nothing on it, because
            // entities are eagerly created for every GameObject even if no components
            // get converted on them.
            EntitiesAssert.ContainsOnly(m_Manager, EntityMatch.Exact());
        }
Exemplo n.º 11
0
    // Start is called before the first frame update
    void Start()
    {
        store         = new BlobAssetStore();
        entityManager = World.DefaultGameObjectInjectionWorld.EntityManager;
        var    settings = GameObjectConversionSettings.FromWorld(World.DefaultGameObjectInjectionWorld, store);
        Entity boid     = GameObjectConversionUtility.ConvertGameObjectHierarchy(boidPrefab, settings);

        Unity.Mathematics.Random rand = new Unity.Mathematics.Random((uint)System.DateTime.Now.Millisecond);

        for (int i = 0; i < boidSize; ++i)
        {
            var        instance = entityManager.Instantiate(boid);
            float3     xyz      = rand.NextFloat3(minBound, maxBound);
            quaternion q        = rand.NextQuaternionRotation();
            entityManager.SetComponentData(instance, new Translation {
                Value = xyz
            });
            entityManager.SetComponentData(instance, new Rotation {
                Value = q
            });

            float3 velocity = math.mul(q, new float3(0, 0, rand.NextFloat(1f, 10f)));
            entityManager.SetComponentData(instance, new SteerVelocity {
                velocity = velocity, lastVelocity = velocity
            });

            if (entityManager.HasComponent <SteerWander>(instance))
            {
                entityManager.AddComponentData(instance, new SteerWanderEdit()
                {
                    qrot = quaternion.identity
                });
            }
        }
    }
Exemplo n.º 12
0
    // Start is called before the first frame update
    void Start()
    {
        GameObjectConversionSettings settings = GameObjectConversionSettings.FromWorld(World.DefaultGameObjectInjectionWorld, null);
        Entity tempCubPrefab = GameObjectConversionUtility.ConvertGameObjectHierarchy(cub, settings);

        EntityManager manager     = World.DefaultGameObjectInjectionWorld.EntityManager;
        Translation   translation = new Translation();

        translation.Value.x = -interval;
        for (int i = 0; i < 100; i++)
        {
            for (int j = 0; j < 100; j++)
            {
                Entity tempCub = manager.Instantiate(tempCubPrefab);

                // Translation 是值类型,不能通过修改此方法来修改位置
                //Translation translation = manager.GetComponentObject<Translation>(tempCub);
                //translation.Value.x += 1;

                translation.Value.x += interval;
                manager.SetComponentData(tempCub, translation);
            }

            translation.Value.x  = -interval;
            translation.Value.y += interval;
        }
    }
Exemplo n.º 13
0
    void Start()
    {
        //UnityEntity = ConvertToEntity(UnitPrefab);

        var em = World.DefaultGameObjectInjectionWorld.EntityManager;

        world = World.DefaultGameObjectInjectionWorld;

        var blob = new BlobAssetStore();
        GameObjectConversionSettings settings = GameObjectConversionSettings.FromWorld(world, blob);

        //unitEntity = GameObjectConversionUtility.ConvertGameObjectHierarchy(UnitPrefab, settings);
        bulletEntity = GameObjectConversionUtility.ConvertGameObjectHierarchy(BulletPrefab, settings);

        //entities bug workaround
        //https://forum.unity.com/threads/invalidoperationexception-object-is-not-initialized-or-has-already-been-destroyed.882484/

        //addSystem<AssignMovePositionSystem>();


        addSystem <SpawnUnitSystem>();
        addSystem <SpawnShootSystem>();
        addSystem <TargetMoveSystem>();
        addSystem <RotateSystem>();
        addSystem <CollectDamageSystem>();
        addSystem <ApplyDamageSystem>();
        addSystem <WaypointsMoveSystem>();
        addSystem <MakeDynamicBodySystem>();
        addSystem <AttackBuildingSystem>();
        addSystem <EndReachedSystem>();
        addSystem <DestroyDeadSystem>();
    }
Exemplo n.º 14
0
    // Start is called before the first frame update
    void Start()
    {
        World world = World.DefaultGameObjectInjectionWorld;

        blobAsset = new BlobAssetStore();

        var conversionSetting = new GameObjectConversionSettings(world, GameObjectConversionUtility.ConversionFlags.AssignName, blobAsset);

        Entity        unitEntity    = GameObjectConversionUtility.ConvertGameObjectHierarchy(prefab, conversionSetting);
        EntityManager entityManager = world.EntityManager;

        NativeArray <Entity> unitsToSpawn = new NativeArray <Entity>(spawnCount, Allocator.Temp);

        entityManager.Instantiate(unitEntity, unitsToSpawn);

        for (int i = 0; i < spawnCount; i++)
        {
            Entity entity = unitsToSpawn[i];
            //entityManager.SetName(entity, name);

            if (disableAtStart)
            {
                entityManager.AddComponent(entity, typeof(Disabled));
            }
        }

        unitsToSpawn.Dispose();
    }
        void CreateObstacleEntities(GameObject prefab, SimulationConfig config)
        {
            var gameConversionSettings = GameObjectConversionSettings.FromWorld(World, null);
            var entityPrefab           = GameObjectConversionUtility.ConvertGameObjectHierarchy(prefab, gameConversionSettings);
            var random = new Random(config.Seed);

            var mapSize   = config.MapSize;
            var antsCount = config.AntsCount;

            for (var i = 1; i <= antsCount; i++)
            {
                var entity   = EntityManager.Instantiate(entityPrefab);
                var position = new float3(random.NextFloat(-5f, 5f) + mapSize * .5f, random.NextFloat(-5f, 5f) + mapSize * .5f, 0);
                EntityManager.SetComponentData(entity, new Translation {
                    Value = position / mapSize
                });
                EntityManager.AddComponentData(entity, new AntTag());
                EntityManager.AddComponentData(entity, new Resource());
                EntityManager.AddComponentData(entity, new Target());
                EntityManager.AddComponentData(entity, new MaterialColor());
                // Setup speed in relationship to map size.
                var speed = EntityManager.GetComponentData <Speed>(entity);
                speed.Max /= mapSize;
                EntityManager.SetComponentData(entity, speed);
                // Setup initial steering.
                var steering = EntityManager.GetComponentData <Steering>(entity);
                steering.Angle = random.NextFloat(0f, 2f * math.PI);
                EntityManager.SetComponentData(entity, steering);
            }

            Enabled = false;
        }
Exemplo n.º 16
0
    // create a single Entity using the Conversion Workflow
    private void ConvertToEntity(float3 position)
    {
        if (entityManager == null)
        {
            Debug.LogWarning("ConvertToEntity WARNING: No EntityManager found!");
            return;
        }

        if (gameObjectPrefab == null)
        {
            Debug.LogWarning("ConvertToEntity WARNING: Missing GameObject Prefab");
            return;
        }

        GameObjectConversionSettings settings = GameObjectConversionSettings.FromWorld(defaultWorld, null);

        entityPrefab = GameObjectConversionUtility.ConvertGameObjectHierarchy(gameObjectPrefab, settings);

        Entity myEntity = entityManager.Instantiate(entityPrefab);

        entityManager.SetComponentData(myEntity, new Translation
        {
            Value = position
        });
    }
        public void ConvertGameObject_WithFilteredBuildSettings_ConversionDoesntRun()
        {
            var scene = SceneManager.GetActiveScene();
            var go    = CreateGameObject("Test Conversion");

            go.transform.localPosition = new Vector3(1, 2, 3);

            var config = BuildConfiguration.CreateInstance((bs) =>
            {
                bs.hideFlags = HideFlags.HideAndDontSave;
                bs.SetComponent(new ConversionSystemFilterSettings("Unity.Transforms.Hybrid"));
            });

            var conversionSettings = new GameObjectConversionSettings
            {
                DestinationWorld   = World,
                BuildConfiguration = config,
                Systems            = TestWorldSetup.GetDefaultInitSystemsFromEntitiesPackage(WorldSystemFilterFlags.GameObjectConversion).ToList()
            };

            GameObjectConversionUtility.ConvertScene(scene, conversionSettings);

            // We still expect to find an Entity, just with nothing on it, because
            // entities are eagerly created for every GameObject even if no components
            // get converted on them.
            EntitiesAssert.ContainsOnly(m_Manager, EntityMatch.Exact());
        }
Exemplo n.º 18
0
    private void Awake()
    {
        if (main != null && main != this)
        {
            Destroy(gameObject);
            return;
        }

        main = this;

        playerScores = new int[2];

        entityManager = World.DefaultGameObjectInjectionWorld.EntityManager;

        blobAssetStore = new BlobAssetStore();
        GameObjectConversionSettings settings =
            GameObjectConversionSettings.FromWorld(World.DefaultGameObjectInjectionWorld, blobAssetStore);

        obstacleEntityPrefab = GameObjectConversionUtility.ConvertGameObjectHierarchy(obstaclePrefab, settings);

        TimeIsOut();

        Entity restart = entityManager.CreateEntity();

        entityManager.AddComponentData(restart, new WaitForRestartTag());
    }
        void CreateFood(GameObject prefab, SimulationConfig config)
        {
            var gameConversionSettings = GameObjectConversionSettings.FromWorld(World, null);
            var entityPrefab           = GameObjectConversionUtility.ConvertGameObjectHierarchy(prefab, gameConversionSettings);

            var mapSize = config.MapSize;
            var random  = new Random(config.Seed);

            var radius = EntityManager.GetComponentData <Radius>(entityPrefab);

            radius.Value /= mapSize;
            var entity   = EntityManager.Instantiate(entityPrefab);
            var angle    = random.NextFloat(0f, 1f) * 2f * math.PI;
            var position = new float3(.5f + math.cos(angle) * .475f, .5f + math.sin(angle) * .475f, 0);

            EntityManager.SetComponentData(entity, new Translation {
                Value = position
            });
            EntityManager.SetComponentData(entity, radius);
            EntityManager.AddComponentData(entity, new NonUniformScale {
                Value = new float3(2, 2, .1f) * radius.Value
            });
            EntityManager.AddComponentData(entity, new FoodTag());

            Enabled = false;
        }
Exemplo n.º 20
0
    private void Awake()
    {
        if (Instance != null)
        {
            Destroy(this);
            return;
        }

        Instance = this;
        //Initialization of pong & dots
        playerScores = new int[2];
        //get a manager reference
        manager = World.DefaultGameObjectInjectionWorld.EntityManager;
        //make some conversions from normal unity scene
        blob = new BlobAssetStore();
        GameObjectConversionSettings settings = GameObjectConversionSettings.FromWorld(World.DefaultGameObjectInjectionWorld, blob);

        BallEntityPrefab = GameObjectConversionUtility.ConvertGameObjectHierarchy(BallPrefab, settings);

        oneSecond = new WaitForSeconds(1f);
        delay     = new WaitForSeconds(respawnDelay);
        //show tutorial info
        StartCoroutine(tutorialTimer(delay));
        //start the game
        StartCoroutine(CountdownAndSpawnBall());
    }
Exemplo n.º 21
0
 private static void RegisterPrefabs(EntityType type, string res)
 {
     prefabs[type] = GameObjectConversionUtility.ConvertGameObjectHierarchy(
         Resources.Load("Item/" + res) as GameObject,
         GameObjectConversionSettings.FromWorld(World.DefaultGameObjectInjectionWorld,
                                                World.DefaultGameObjectInjectionWorld.GetOrCreateSystem <ConvertToEntitySystem>().BlobAssetStore));
 }
        protected void TestConvertedData <T>(Action <NativeArray <T> > checkValues, int assumeCount) where T : struct, IComponentData
        {
            var world = new World("Test world");

            try
            {
                using (var blobAssetStore = new BlobAssetStore())
                {
                    var settings = GameObjectConversionSettings.FromWorld(world, blobAssetStore);
                    GameObjectConversionUtility.ConvertGameObjectHierarchy(Root, settings);

                    using (var group = world.EntityManager.CreateEntityQuery(typeof(T)))
                    {
                        using (var components = group.ToComponentDataArray <T>(Allocator.Persistent))
                        {
                            Assume.That(components, Has.Length.EqualTo(assumeCount));
                            checkValues(components);
                        }
                    }
                }
            }
            finally
            {
                world.Dispose();
            }
        }
Exemplo n.º 23
0
    void Awake()
    {
        // get world and entity manager to keep lines short
        defaultWorld  = World.DefaultGameObjectInjectionWorld;
        entityManager = defaultWorld.EntityManager;

        // set map system
        defaultWorld.GetExistingSystem <ConstrainToMapSystem>().Enabled = (mapSystem == MapSystem.Constrain);
        defaultWorld.GetExistingSystem <WrapToMapSystem>().Enabled      = (mapSystem == MapSystem.Wrap);

        // convert prefabs into entities
        blobAssetStore = new BlobAssetStore();
        GameObjectConversionSettings settings = GameObjectConversionSettings.FromWorld(defaultWorld, blobAssetStore);

        foodSpawnerEntityPrefab = GameObjectConversionUtility.ConvertGameObjectHierarchy(foodSpawnerPrefab, settings);
        foodEntityPrefab        = GameObjectConversionUtility.ConvertGameObjectHierarchy(foodPrefab, settings);

        // map will only be used here, so no need to make it public
        Entity mapEntityPrefab = GameObjectConversionUtility.ConvertGameObjectHierarchy(mapGameObject, settings);

        mapEntity = entityManager.Instantiate(mapEntityPrefab);
        InitializeMap();

        // name entities accordingly
        entityManager.SetName(foodSpawnerEntityPrefab, "foodSpawner");
        entityManager.SetName(foodEntityPrefab, "food");
        entityManager.SetName(mapEntity, "map");

        // initialize arrays
        foodSpawnerOutputLocations = new float3[foodSpawnerAmount];
    }
Exemplo n.º 24
0
    void OnEnable()
    {
        if (this.enabled)
        {
            random = new Unity.Mathematics.Random();
            random.InitState(seed);
            sourceEntitys   = new List <Entity>();
            sourceColliders = new List <BlobAssetReference <Collider> >();
            sourceJoints    = new List <BlobAssetReference <JointData> >();

            float3 gravity = new float3(0, 0.0f, 0);//float3.zero;

            base.init(gravity, false /* don't add the control script from the base physics */);

            for (int i = 0; i < prefabs.Count; i++)
            {
                var prefab   = prefabs[i];
                var settings = GameObjectConversionSettings.FromWorld(World.DefaultGameObjectInjectionWorld, new BlobAssetStore());
                // Create entity prefab from the game object hierarchy once
                var sourceEntity  = GameObjectConversionUtility.ConvertGameObjectHierarchy(prefab, settings);
                var entityManager = BasePhysicsDemo.DefaultWorld.EntityManager;
                sourceEntitys.Add(sourceEntity);

                var sourceCollider = entityManager.GetComponentData <PhysicsCollider>(sourceEntity).Value;
                sourceColliders.Add(sourceCollider);
                //var sourceJoint = entityManager.GetComponentData<PhysicsJoint>(sourceEntity).Value;
                //sourceJoints.Add(sourceJoint);
            }

            _sketchPlaneStartZ = sketchPlane.transform.position.z;
        }
    }
Exemplo n.º 25
0
    private void Start()
    {
        //参数检查
        if (goPrefab)
        {
            Debug.Log(GetType() + "/Start()/游戏预设没有指定");
        }

        //游戏对象转为实体(entity)
        var settings = GameObjectConversionSettings.FromWorld(World.DefaultGameObjectInjectionWorld, null);

        entity = GameObjectConversionUtility.ConvertGameObjectHierarchy(goPrefab, settings);
        //得到实体管理器(EntityManger)
        entityMgr = World.DefaultGameObjectInjectionWorld.EntityManager;
        //按照指定数量,克隆大量实体,且指定分布位置
        for (int x = 0; x < XNum; x++)
        {
            for (int y = 0; y < YNum; y++)//z轴
            {
                //从“实体预设”,大量克隆实体
                Entity entityClone = entityMgr.Instantiate(entity);
                //对克隆实体,定义其初始位置
                Vector3 position = transform.TransformPoint(new float3(x - XNum / 2, noise.cnoise(new float2(x, y) * 0.21f), y - YNum / 2));
                //实体管理器设置其中的组件参数
                entityMgr.SetComponentData(entityClone, new Translation()
                {
                    Value = position
                });
                //把定义的组件加入实体管理器
                entityMgr.AddComponentData(entityClone, new Movement {
                    MoveSpeed = 1f
                });
            }
        }
    }
Exemplo n.º 26
0
    private void InstantiateSpaceShips(GameObjectConversionSettings settings)
    {
        // Convert prefab to entity prefab
        Entity spaceShipEntityPrefab = GameObjectConversionUtility.ConvertGameObjectHierarchy(spaceShipPrefab, settings);
        Entity bulletEntityPrefab    = GameObjectConversionUtility.ConvertGameObjectHierarchy(bulletPrefab, settings);

        for (int i = 0; i < numberOfSpaceShipsToInstantiate; i++)
        {
            // Instantiate Entity to default world
            Entity entityInstance = manager.Instantiate(spaceShipEntityPrefab);

            // Compute initial planet position
            Vector3 initialPosition = ComputeRandomSpawnSpaceShipInitialPosition();

            // Set entity position
            manager.SetComponentData(entityInstance, new Translation()
            {
                Value = initialPosition
            });

            // Set entity target position
            manager.SetComponentData(entityInstance, new SpaceShipData()
            {
                supplyPointIndex   = ECSDataManager.instance.GetRandomSupplyPoint(),
                isNearToPlanet     = false,
                planetIndex        = ECSDataManager.instance.GetRandomPlanet(),
                bulletEntityPrefab = bulletEntityPrefab
            });
        }
    }
Exemplo n.º 27
0
        Entity CreateCard(float3 pos, int value, Material mat, EntityManager dstManager, GameObjectConversionSystem conversionSystem)
        {
            // extract the card from the gameobject
            GameObjectConversionSettings settings = GameObjectConversionSettings.FromWorld(dstManager.World, conversionSystem.BlobAssetStore);
            Entity card = GameObjectConversionUtility.ConvertGameObjectHierarchy(cardGameObject.gameObject, settings);

            // create the card
            card = dstManager.Instantiate(card);

            quaternion startingRot = quaternion.identity;

            // set the card value and face
            Card cardData = dstManager.GetComponentData <Card>(card);

            cardData.value = value;
            RenderMesh cardFace = dstManager.GetSharedComponentData <RenderMesh>(cardData.face);

            cardFace.material = mat;
            dstManager.SetSharedComponentData <RenderMesh>(cardData.face, cardFace);
            dstManager.SetComponentData <TargetRotation>(card, new TargetRotation {
                target = startingRot
            });
            dstManager.SetComponentData <Card>(card, cardData);

            // set position and bounding box
            dstManager.SetComponentData <Translation>(card, new Translation {
                Value = pos
            });
            BoundingBox box = dstManager.GetComponentData <BoundingBox>(card);

            box.aabb.Center = pos;
            dstManager.SetComponentData <BoundingBox>(card, box);
            return(card);
        }
Exemplo n.º 28
0
    // Start is called before the first frame update
    void Start()
    {
        em  = World.DefaultGameObjectInjectionWorld.EntityManager;
        bas = new BlobAssetStore();
        GameObjectConversionSettings gocs = GameObjectConversionSettings.FromWorld(World.DefaultGameObjectInjectionWorld, bas);

        projectileEntity = GameObjectConversionUtility.ConvertGameObjectHierarchy(projectilePrefab, gocs);
        convertedEntity  = GameObjectConversionUtility.ConvertGameObjectHierarchy(prefabToSpawn, gocs);

        if (colliderMesh != null)
        {
            col = CreateSphereCollider(colliderMesh);
        }
        em.AddComponent <ShooterComponentData>(convertedEntity);
        em.SetComponentData(convertedEntity, new Translation {
            Value = transform.position
        });
        em.SetComponentData(convertedEntity, new ShooterComponentData
        {
            colliderCast       = col,
            projectile         = projectileEntity,
            firingInterval     = projectileFiringInterval,
            projectileSpeed    = projectileSpeed,
            projectileLifeTime = projectileLifeTime
        });
        for (int i = 0; i <= numberOfShooters; i++)
        {
            em.Instantiate(convertedEntity);
            position = (float3)transform.position + (new float3(1.5f * i, 0, 0));
            em.SetComponentData(convertedEntity, new Translation {
                Value = position
            });
        }
    }
Exemplo n.º 29
0
        void Start()
        {
            // Create entity prefab from the game object hierarchy once
            BlobAssetStore blobAsset = new BlobAssetStore();

            var settings      = GameObjectConversionSettings.FromWorld(World.DefaultGameObjectInjectionWorld, blobAsset);
            var prefab        = GameObjectConversionUtility.ConvertGameObjectHierarchy(Prefab, settings);
            var entityManager = World.DefaultGameObjectInjectionWorld.EntityManager;

            for (var x = 0; x < CountX; x++)
            {
                for (var y = 0; y < CountY; y++)
                {
                    // Efficiently instantiate a bunch of entities from the already converted entity prefab
                    var instance = entityManager.Instantiate(prefab);

                    // Place the instantiated entity in a grid with some noise
                    var position = transform.TransformPoint(new float3(x * 1.3F, noise.cnoise(new float2(x, y) * 0.21F) * 2, y * 1.3F));
                    entityManager.SetComponentData(instance, new Translation {
                        Value = position
                    });
                }
            }

            blobAsset.Dispose();
        }
Exemplo n.º 30
0
    protected override void OnCreate()
    {
        var manager  = World.DefaultGameObjectInjectionWorld.EntityManager;
        var settings = GameObjectConversionSettings.FromWorld(World.DefaultGameObjectInjectionWorld, null);

        Cube = Resources.Load <GameObject>("Cube");

        var _cube = GameObjectConversionUtility.ConvertGameObjectHierarchy(Cube, settings);

        var mesh = Cube.GetComponent <MeshFilter>().sharedMesh;

        var rMesh = new RenderMesh()
        {
            mesh           = mesh,
            material       = Resources.Load <Material>("Material"),
            receiveShadows = true,
            castShadows    = UnityEngine.Rendering.ShadowCastingMode.On
        };


        for (int i = 0; i < 100; i++)
        {
            for (int ii = 0; ii < 100; ii++)
            {
                var entity = manager.Instantiate(_cube);
                manager.AddComponentData(entity, new Translation()
                {
                    Value = new float3(i * 2, 0, ii * 2)
                });
                manager.AddComponentData(entity, new LocalToWorld());
                manager.AddSharedComponentData(entity, rMesh);
            }
        }
    }