public void Alloc(GameObject prefab, Transform parent, int count) { if (ObjectsPool.ContainsKey(prefab)) { int index = 0; while (ObjectsPool[prefab].Count > index) { if (ObjectsPool[prefab][index] == null) { ObjectsPool[prefab].RemoveAt(index); } else { index++; } } } else { ObjectsPool.Add(prefab, new List <GameObject>()); } while (ObjectsPool[prefab].Count < count) { Recycle(prefab, PrefabFactory.Instantiate(prefab, parent), parent); } while (ObjectsPool[prefab].Count > count) { Destroy(ObjectsPool[prefab][0]); ObjectsPool[prefab].RemoveAt(0); } }
/// <summary> /// Updates all of the regions. /// </summary> void UpdateRegions() { Vector3 cameraPosition = _camera.position; _currentRegion = (int)(cameraPosition.z / _regionSize.y); if (_currentRegion > _previousRegion) {//if we have moved up a region. //destroy the bottom regions Destroy(_regions[RegionOrder.Bot].gameObject); int size = _regions.Count - 1; for (int i = 0; i < size; i++) {//shift all of the regions down _regions[(RegionOrder)i] = _regions[(RegionOrder)i + 1]; } //create and intiialize a new regions for the top. GameObject regionClone = PrefabFactory.CreateGameObject(PrefabFactory.Prefab.Region); Vector3 position = regionClone.transform.position; position.z = _regions[(RegionOrder)((int)RegionOrder.Top - 1)].position.z + _regionSize.y; regionClone.transform.position = position; Region region = regionClone.GetComponent <Region>(); region.Setup(_halfRegionSize); _regions[RegionOrder.Top] = region; } _previousRegion = _currentRegion; }
public override void OnLoad() { PrefabFactory prefabFactory = new PrefabFactory(world.EntityManager); player = prefabFactory.Create(PrefabIds.PLAYER); player.GetComponent <Transform>().Position = new Vector2(250, 50); }
public override void Setup(IEventSystem eventSystem, IPoolManager poolManager, GroupFactory groupFactory) { base.Setup(eventSystem, poolManager, groupFactory); var group = GroupFactory.Create(new Type[] { typeof(SpawnerComponent) }); group.OnAdd().Subscribe(entity => { var spawner = entity.GetComponent <SpawnerComponent>(); var delay = TimeSpan.FromSeconds(0f); var interval = TimeSpan.FromSeconds(spawner.SpawnTime); Observable.Timer(delay, interval).Subscribe(_ => { // if(playerHealth.currentHealth <= 0f) // { // return; // } // Instantiate (enemy, spawnPoints[spawnPointIndex].position, spawnPoints[spawnPointIndex].rotation); var instance = PrefabFactory.Instantiate(spawner.Prefab, spawner.transform); // instance.transform.SetParent(spawner.transform, false); instance.transform.position = spawner.transform.position; instance.transform.rotation = spawner.transform.rotation; }).AddTo(spawner); }).AddTo(this); }
/// <summary> /// Generates obstacles randomly around the region. /// Actiavtes one of its walls. /// </summary> /// <param name="prefab"></param> /// <param name="positionsOccupied"></param> void GenerateObstacles(ref List <CreationData> positionsOccupied) { int obstacleCount = 0; int obstaclesToCreate = Random.Range(1, DataManager.maximumObstacles + 1); ActivateWall(ref positionsOccupied); Vector2 size = PrefabFactory.GetSize(PrefabFactory.Prefab.Wall) * 0.5f; Vector2 failedToPosition = new Vector2(-1, -1); while (obstacleCount < obstaclesToCreate) { Vector2 position = GetAvailabePosition(size, ref positionsOccupied); if (position != failedToPosition) { positionsOccupied.Add(new CreationData(position, size)); GameObject clone = PrefabFactory.CreateGameObject(PrefabFactory.Prefab.Wall); Transform cloneTransform = clone.transform; cloneTransform.position = new Vector3(position.x, cloneTransform.position.y, position.y); cloneTransform.parent = _transform; _obstacles.Add(clone); obstacleCount++; } else { break; } } }
/// <summary> /// Generates YellowBall randomly around the region. /// </summary> /// <param name="positionsOccupied"></param> void GenerateYellowBalls(ref List <CreationData> positionsOccupied) { Vector2 size = PrefabFactory.GetSize(PrefabFactory.Prefab.YellowBall) * 0.5f; Vector2 failedToPosition = new Vector3(-1, -1); int yellowBallCount = 0; int yellowBallsToCreate = Random.Range(0, ConstHolder.MAX_YELLOWBALLS); while (yellowBallCount != yellowBallsToCreate) { Vector2 position = GetAvailabePosition(size, ref positionsOccupied); if (position != failedToPosition) { positionsOccupied.Add(new CreationData(position, size)); GameObject clone = PrefabFactory.CreateGameObject(PrefabFactory.Prefab.YellowBall); clone.transform.position = new Vector3(position.x, clone.transform.position.y, position.y); clone.transform.parent = _transform; YellowBall yellowBall = clone.GetComponent <YellowBall>(); yellowBall.Initialize(); _yellowBalls.Add(yellowBall); yellowBallCount++; } else { break; } } }
private void OnBulletHitCharacter(BulletComponent bullet, CharacterComponent character) { character.Hit(); if (character.CurrentHealth <= 0 && bullet.Source != null) { bullet.Source.Player.IncrementScore((bullet.Source == character) ? -1 : 1); //GameObject go = PrefabFactory.Pop("bulletexplode"); //go.transform.position = bullet.transform.position; //this.DelayAction(8, () => PrefabFactory.Push("bulletexplode", go)); GameObject explode = PrefabFactory.Pop("vfxexplode"); explode.transform.position = bullet.transform.position + (UnityEngine.Camera.main.transform.position - bullet.transform.position).normalized; this.DelayAction(5, () => PrefabFactory.Push("vfxexplode", explode)); GameObject shock = PrefabFactory.Pop("shockwave"); shock.transform.position = bullet.transform.position; shock.transform.LookAt(UnityEngine.Camera.main.transform); this.DelayAction(2.2f, () => PrefabFactory.Push("shockwave", shock)); string sfxName = Random.Range(0f, 1f) > 0.5 ? "sfxdeath1" : "sfxdeath2"; GameObject sfx = PrefabFactory.Pop(sfxName); sfx.transform.position = bullet.transform.position; this.DelayAction(4f, () => PrefabFactory.Push(sfxName, sfx)); } PrefabFactory.Push("bullet", bullet.gameObject); }
public override void OnLoad() { PrefabFactory prefabFactory = new PrefabFactory(world.EntityManager); gameOver = prefabFactory.CreateSpriteText("Game OVER!"); gameOver.AddComponent(new GameOverBehaviour()); }
private void Construct(DataNetContainer dataNetContainer, PrefabFactory prefabFactory, NetSelectionElementInstaller elementPrefab) { _dataNetContainer = dataNetContainer; _prefabFactory = prefabFactory; _elementPrefab = elementPrefab; }
public Pool(GameObject prefab, PrefabFactory prefabFactory, NetworkPrefabFactory networkPrefabFactory) { inactiveParts = new List <IEntity>(); activeParts = new List <IEntity>(); this.prefab = prefab; PrefabFactory = prefabFactory; NetworkPrefabFactory = networkPrefabFactory; }
private void InstantiateStage(Stage stage) { for (var i = 0; i < Stage.Width; i++) { for (var j = 0; j < Stage.Height; j++) { var cell = stage.GetCell(i, j); var pos = new Vector3(i, 0, j); switch (cell.CellType) { case CellType.Hard: PrefabFactory.Create <HardRockView>(StagePrefabPathDef.HardRock, _stageRootTransform, pos); break; case CellType.Medium: PrefabFactory.Create <MediumRockView>(StagePrefabPathDef.MediumRock, _stageRootTransform, pos); break; case CellType.Normal: PrefabFactory.Create <NormalRockView>(StagePrefabPathDef.NormalRock, _stageRootTransform, pos); break; case CellType.Treasure: PrefabFactory.Create <TreasureCellView>(StagePrefabPathDef.TreasureCell, _stageRootTransform, pos); break; case CellType.Trap: break; case CellType.ArrowUp: PrefabFactory.Create <TmpArrowCellView>(StagePrefabPathDef.TmpArrowCell, _stageRootTransform, pos); break; case CellType.ArrowDown: PrefabFactory.Create <TmpArrowCellView>(StagePrefabPathDef.TmpArrowCell, _stageRootTransform, pos); break; case CellType.ArrowRight: PrefabFactory.Create <TmpArrowCellView>(StagePrefabPathDef.TmpArrowCell, _stageRootTransform, pos); break; case CellType.ArrowLeft: PrefabFactory.Create <TmpArrowCellView>(StagePrefabPathDef.TmpArrowCell, _stageRootTransform, pos); break; default: throw new ArgumentOutOfRangeException(); } } } }
private IEnumerator Start() { yield return(null); for (int i = 0; i < ShopView.GetElementCount(); i++) { var go = PrefabFactory.Instantiate(ShopElementPrefab, ShopView.Content); ShopView.Elements.Add(go.GetComponent <ShopElement>()); } }
protected override void OnEventFired(object source, EntityCreationStartingEventArgs args) { EntityPrefab prefabType = ComputePrefabType(args.EntityGuid); IMovementData movementData = MovementDataMappable.RetrieveEntity(args.EntityGuid); //load the entity's prefab from the factory GameObject prefab = PrefabFactory.Create(prefabType); GameObject entityGameObject = GameObject.Instantiate(prefab, movementData.InitialPosition, Quaternion.Euler(0, movementData.Rotation, 0)); OnEntityWorldRepresentationCreated?.Invoke(this, new EntityWorldRepresentationCreatedEventArgs(args.EntityGuid, entityGameObject)); }
private static ICanvas CreateCanvas(ICamera renderCamera, Transform rootTransform, string canvasPrefabPath, string touchBlockPrefabPath) { var canvas = PrefabFactory.Create <CanvasBase>(canvasPrefabPath, rootTransform); canvas.SetCamera(renderCamera); var touchBlockPresenter = CreateTouchBlockPresenter(canvas, touchBlockPrefabPath); canvas.SetTouchBlockPresenter(touchBlockPresenter); return(canvas); }
private void OnBulletShoot(CharacterComponent owner, Vector3 position, Vector3 direction) { GameObject go = PrefabFactory.Pop("bullet"); go.transform.position = position; go.GetComponent <BulletComponent>().Setup(owner, direction); GameObject sfx = PrefabFactory.Pop("sfxshoot"); sfx.transform.position = position; this.DelayAction(2f, () => PrefabFactory.Push("sfxshoot", sfx)); }
void Awake() { if (PrefabFactory.Instance == null) { PrefabFactory.Instance = this; DontDestroyOnLoad(this.gameObject); } else { GameObject.Destroy(this.gameObject); } }
/// <summary> /// Creates a unit and sets it in the rotation and position required. /// Unit is initialized based on its type. /// </summary> /// <param name="unitDataContainer"></param> /// <param name="unitSize"> size of a unit</param> /// <param name="regionSize"></param> /// <param name="type"></param> /// <returns>game object</returns> Unit SetupUnit(UnitType type, ref GameObject container, Vector3 spawnPosition, Vector3 spawnEulerAngle) { Unit unit = PrefabFactory.CreateUnit(type); Vector2 unitSize = PrefabFactory.GetSize(PrefabFactory.Prefab.Unit); unit.transform.position = spawnPosition; unit.transform.eulerAngles = spawnEulerAngle; unit.transform.parent = container.transform; unit.Initialize(type); return(unit); }
private GameObject CreateUser(bool isLocalPlayer, bool isRoomOwner, int userId, string userName, int totalCount, int winCount) { return(PrefabFactory.Instantiate(UserPrefab, null, false, go => { var userComponent = go.GetComponent <UserComponent>(); userComponent.IsLocalPlayer = isLocalPlayer; userComponent.IsRoomOwner.Value = isRoomOwner; userComponent.UserId = userId; userComponent.UserName.Value = userName; userComponent.TotalCount.Value = totalCount; userComponent.WinCount.Value = winCount; })); }
/// <summary> /// Creates all of entities here and initializes them. /// </summary> void Start() { PrefabFactory.Initialize(); ParticleSystemFactory.Initialize(); GenerateRegions(); GeneratePlayers(); SetupSpotLights(); SetupCamera(); AudioManager.instance.PlaySoundEffect(AudioManager.SoundEffect.RoundStart); }
public void CreateView(Transform panelTransform, PrefabFactory factoryPrefab) { if (factoryPrefab == null) { return; } if (panelTransform == null) { return; } view = factoryPrefab.GetNote(); view.transform.SetParent(panelTransform); view.transform.localScale = new Vector3(1, 1, 1); }
private void CreateShadowPrefabs() { var platformShadow = GameObjectFactory .New() .With(new Sprite() { Texture = TextureUtil.CreateTexture(64, 64, Color.Black), Tint = Color.Lerp(Color.White, Color.Transparent, 0.2f) }) .Create(); platformShadow.Visible = false; PrefabFactory.Instantiate(platformShadow); blockInfo.AddInfo("platform", platformShadow, true); }
/// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. DefaultFont = Content.Load <SpriteFont>("Default"); spriteBatch = new SpriteBatch(GraphicsDevice); //PrefabFactory.RegisterPrefab("machine gun", () => GameObjectFactory.New() // .WithTexture(TextureUtil.CreateTexture(16, 16, Color.Red)) // .With(new Weapon() { FireRate = 0.5f }) // .Create()); //PrefabFactory.RegisterPrefab("player", () => GameObjectFactory.New() // .AtPosition(new Vector2(0)) // .WithTexture(TextureUtil.CreateTexture(64, 128, Color.Black)) // .With(new VelocityController()) // .With(new ShipEngine()) // .With(new PlayerController()) // .With(new Drag()) // .With(new ScreenWrapper()).With(new ParticleEmitter()) // .WithChild("machine gun", new Vector2(0, -1)) // .Create()); //PrefabFactory.RegisterPrefab("bullet", () => GameObjectFactory.New() // .WithTexture(TextureUtil.CreateTexture(16, 16, Color.Yellow)) // .With(new VelocityController()) // .With(new BulletController()) // .With(new ScreenWrapper()) // .Create()); PrefabFactory.RegisterPrefab("unitbox", () => GameObjectFactory.New() .WithTexture(TextureUtil.CreateTexture(64, 64, Color.Black)) .With(new Collider() { Body = BodyFactory.CreateRectangle(PhysicsWorld.World, 1, 1, 1) }) .Create()); PrefabFactory.RegisterPrefab("cursor", () => GameObjectFactory.New() .WithTexture(TextureUtil.CreateTexture(64, 64, Color.Red)) .With(new SimpleController()).With(new Collider() { Body = BodyFactory.CreateRectangle(PhysicsWorld.World, 1, 1, 1), BodyType = BodyType.Dynamic }) .Create()); GameObjectManager.Start(); }
private void Awake() { _pf = FindObjectOfType <PrefabFactory>(); if (_pf == null) { throw new Exception("Не найдена фабрика префабов"); } _ui = FindObjectOfType <UIController>(); if (_ui == null) { throw new Exception("Не найден контроллер UI"); } GameEvent.OnSwipe += GameEventOnSwipe; }
protected override void HandleEvent(CharacterFriendAddedEventArgs args) { UnityAsyncHelper.UnityMainThreadContext.PostAsync(async() => { string characterName = await NameQueryable.RetrieveAsync(args.FriendGuid); GameObject slotObject = GameObject.Instantiate(PrefabFactory.Create(EntityPrefab.CharacterFriendSlot)); IUICharacterFriendSlot characterFriendSlot = slotObject.GetComponent <IUICharacterFriendSlot>(); //We're on the main thread here, we can create the tab. FriendWindowRoot.Parent(slotObject); //TODO: Query for name. characterFriendSlot.Text = characterName; characterFriendSlot.LocationText.Text = "Unknown"; }); }
public static PrefabFactory FromBaseObject(BaseObject baseObj) { if (baseObj == null || baseObj.NativeObject == IntPtr.Zero) { return(null); } PrefabFactory obj = baseObj as PrefabFactory; if (object.Equals(obj, null)) { obj = new PrefabFactory(CreatedWhenConstruct.CWC_NotToCreate); obj.BindNativeObject(baseObj.NativeObject, "CPrefabFactory"); obj.IncreaseCast(); } return(obj); }
/// <inheritdoc /> public GameObject Create(TCreationContext context) { if (Logger.IsDebugEnabled) { Logger.Debug($"Creating entity. Type: {context.EntityGuid.EntityType} Id: {context.EntityGuid.EntityId}"); } //load the entity's prefab from the factory GameObject prefab = PrefabFactory.Create(context.PrefabType); GameObject entityGameObject = GameObject.Instantiate(prefab, context.MovementData.InitialPosition, Quaternion.Euler(0, 0, 0)); if (context.EntityGuid.EntityType == EntityType.Player) { CharacterControllerMappable[context.EntityGuid] = entityGameObject.GetComponent <CharacterController>(); } GameObjectToEntityMap.ObjectToEntityMap.Add(entityGameObject, context.EntityGuid); //TODO: Better handle initial movement/position data GuidToMovementInfoMappable.Add(context.EntityGuid, context.MovementData); GuidToGameObjectMappable.Add(context.EntityGuid, entityGameObject); //TODO: Is it best to do this here? if (!MovementHandlerService.TryHandleMovement(context.EntityGuid, context.MovementData)) { throw new InvalidOperationException($"Cannot handle MovementType: {context.MovementData.GetType().Name} for Entity: {context.EntityGuid}"); } //TODO: We need a better way to handle the entity data collection, we're casting and downcasting in afew spots //Entity data needs to be change trackable var changeTrackableEntityDataCollection = new ChangeTrackingEntityFieldDataCollectionDecorator <EntityDataFieldType>((IEntityDataFieldContainer <EntityDataFieldType>)context.EntityData); //Now we should add the entity data to the mappable collection //This lets it be looked up in both ways FieldDataContainers.Add(context.EntityGuid, changeTrackableEntityDataCollection); ChangeTrackableEntityDataFieldContainers.Add(context.EntityGuid, changeTrackableEntityDataCollection); EntityAsyncLockMap.Add(new KeyValuePair <NetworkEntityGuid, AsyncReaderWriterLock>(context.EntityGuid, new AsyncReaderWriterLock())); return(entityGameObject); }
public void ReceiveChatMessage(int tabId, [NotNull] string text) { if (text == null) { throw new ArgumentNullException(nameof(text)); } if (tabId <= 0) { throw new ArgumentOutOfRangeException(nameof(tabId)); } GameObject textObject = GameObject.Instantiate(PrefabFactory.Create(EntityPrefab.MessageBoxText)); IUIText uiText = RetrieveUITextComponent(textObject); uiText.Text = text; //Parent to the message box. ChatWindow.Parent(textObject); }
public void CreateSpriteView(Transform panelTransform, PrefabFactory factoryPrefab) { if (factoryPrefab == null) { return; } if (panelTransform == null) { return; } view = factoryPrefab.GetNoteSprite(); view.transform.SetParent(panelTransform); view.transform.localScale = new Vector3(100, 100, 100); mathUtil.ix = (xId - 2) * 320; this.panelTransform = panelTransform; // ラインインスタンス if (state == NoteState.KillLinkStart) { lineEffect = factoryPrefab.GetLineEffect(); lineEffect.init(); } // 同時連結ノーツの場合にラインを生成します if (hasLine) { lineMathUtil = mathUtil.Clone(); var centerX = (float)xId + (float)lineLength * 0.5f; lineMathUtil.ix = (centerX - 2) * 320; connecter = factoryPrefab.GetNoteConnecter(); connecter.transform.SetParent(panelTransform); connecter.transform.localScale = new Vector3(100, 100, 100); } }
public IEnumerator InitView(string viewId) { if (!Contains(viewId)) { throw new Exception("ViewManager: does not contain such key"); } if (_gameObjects.ContainsKey(viewId)) { yield break; } if (!ResourceManager.Loaded(viewId)) { throw new Exception("ViewManager: has not loaded this object yet"); } var gameObject = PrefabFactory.FromResource(viewId); gameObject.SetActive(false); SceneRoot.AddChild(gameObject); _gameObjects.Add(viewId, gameObject); }
public override void Start() { map = new MapInfo(); base.Start(); PrefabInitializer.AddRunnerGamePrefabs(PrefabFactory); cursor = GameObjectFactory.New().With(new MouseComponent()).Create(); PrefabFactory.Instantiate(cursor); camera = CameraBuilder.CreateCamera(cursor.Transform); PrefabFactory.Instantiate(camera); var scene = GameObjectFactory.New().Create(); PrefabFactory.Instantiate(scene); map.Scene = new PrefabInfo() { PrefabName = "empty", Children = new List <PrefabInfo>() }; //Instantiate the action manager so we can undo/redo actionManager = new ActionManager(map, scene, PrefabFactory); //Create placer placer = new Placer(); placer.Manager = actionManager; var placerObj = GameObjectFactory.New() .With(placer) .Create(); PrefabFactory.Instantiate(placerObj); CreateShadowPrefabs(); SetPlacing("platform"); }