public void Awake() { referenceWeapon = weaponPrefab.GetComponent<AbstractWeapon>(); if (referenceWeapon.transform.GetComponent<TrailRenderer>()) { hasTrail = true; trailTime = referenceWeapon.transform.GetComponent<TrailRenderer>().time; } Register(referenceWeapon.Name, this); weaponPool = new GameObjectPool(weaponPrefab, maxPoolSize, initialPoolSize, transform); if (impactPrefabs != null && impactPrefabs.Length > 0) { impactPools = new GameObjectPool[impactPrefabs.Length]; for (int i = 0; i < impactPrefabs.Length; i++) { impactPools[i] = new GameObjectPool(impactPrefabs[i], maxImpactPoolSize, initialImpactPoolSize, transform); } } if (muzzleFlashPrefabs != null && muzzleFlashPrefabs.Length > 0) { muzzlePools = new GameObjectPool[muzzleFlashPrefabs.Length]; for (int i = 0; i < muzzleFlashPrefabs.Length; i++) { muzzlePools[i] = new GameObjectPool(muzzleFlashPrefabs[i], maxMuzzleFlashPoolSize, initialMuzzleFlashPoolSize, transform); } } impactIdx = 0; muzzleIdx = 0; }
void Awake() { mInstance = this; testEnemyPool = new GameObjectPool(testEnemy, 1); projectilePool = new GameObjectPool(projectile, 10); }
void Start() { _trail = Component<TrailRenderer>(); _pool = Scene.Object<TrailDetectorPool>().Pool; _lastDetector = _pool.RequestObject<TrailDetector>(); _lastDetector.gameObject.layer = _layer; }
void Start() { StartCoroutine(DestroyMe(X)); if(Pooled) { pool = GameObjectPool.GetPool(PoolName); } }
void OnPoolCreate(GameObjectPool pool) { _pool = pool; GetComponent<ParticleSystem>().GetComponent<Renderer>().enabled = true; GetComponent<ParticleSystem>().time = 0; GetComponent<ParticleSystem>().Clear(true); GetComponent<ParticleSystem>().Play(true); }
public void GameStartUp() { ObjectPool = (GameObject.Instantiate(Resources.Load("Prefabs/System/GameObjectPool")) as GameObject).GetComponent<GameObjectPool>(); IOManager = (GameObject.Instantiate(Resources.Load("Prefabs/System/IOManager")) as GameObject).GetComponent<IOManager>(); UICore = (GameObject.Instantiate(Resources.Load("Prefabs/UI/UIRoot")) as GameObject).GetComponent<UICore>(); GameState = new GameStateHandler(); GameState.Initialize(); PlayerInfo = new PlayerInfo(); EventManager = new EventManager(); }
/// <summary> /// Gets the pool. /// </summary> /// <returns>The pool.</returns> /// <param name="targetPreFabrication">Target pre fabrication.</param> public GameObjectPool GetPool(GameObject targetPreFabrication) { if(pools.ContainsKey(targetPreFabrication)) { return(pools[targetPreFabrication]); } else { GameObjectPool pool = new GameObjectPool(targetPreFabrication, defaultSize); pools.Add(targetPreFabrication, pool); return(pool); } }
void Awake() { enemyPrefab = Resources.Load<GameObject>("Prefabs/Enemy"); enemyPool = new GameObjectPool<GameObject>(enemyCount,enemyPrefab,(GameObject obj) => { GameObject clone = GameObject.Instantiate(enemyPrefab); clone.SetActive(false); return clone; }); }
void initSpriteComponentPool() { // init sprite component pool if (transform.Find ("SpriteComponentPool") == null) throw new InvalidOperationException("Sprite component pool is missing."); spriteComponentPool = transform.Find ("SpriteComponentPool").GetComponent<GameObjectPool> (); spriteComponentPool.init (); // init sprite pool if (transform.Find ("SpriteComponentPool").transform.Find ("SpritePool") == null) throw new InvalidOperationException("Sprite pool is missing."); spritePool = transform.Find ("SpriteComponentPool").transform.Find ("SpritePool").GetComponent<GameObjectPool> (); spritePool.init (); }
void Awake() { Assert.IsNull(Instance, "More than 1 instance of PooledDB detected. ONLY HAVE 1 IN THE SCENE PLZ"); Instance = this; Assert.AreEqual(m_ParticlePrefabs.Length, Helper.CountEnum(typeof(Pools.Particles))); Assert.AreEqual(m_PickUpsPrefabs.Length, Helper.CountEnum(typeof(Pools.PickUps))); // Set up the object pools for each entry for (int i = 0; i < Helper.CountEnum(typeof(Pools.Particles)); i++) { m_Particles[i] = new GameObjectPool(0, m_ParticlePrefabs[i], this.gameObject); } for (int i = 0; i < Helper.CountEnum(typeof(Pools.PickUps)); i++) { m_PickUps[i] = new GameObjectPool(0, m_PickUpsPrefabs[i], this.gameObject); } }
// public static GameObject GetOrCreate(ABAsset asset) { // return GetOrCreate(asset.ab, asset.prefab); // } // 取得一个对象,如果指定parent,则创建的对象将会使用指定的parent,否则放在默认的池节点 public GameObject GetOrCreate(string abname, string name, Transform parent = null) { GameObjectPool pool; string key = GameObjectPool.GetKey(abname, name); if (!pool_dict_.TryGetValue(key, out pool)) { pool = new GameObjectPool(root_, abname, name); pool_dict_.Add(key, pool); } GameObject obj = pool.GetOrCreate(); if (parent != null && obj != null) { obj.transform.SetParent(parent); // ResourceManager.Identify(obj); } return(obj); }
private void OnEventEntityDetach(WorldEntity worldEntity) { if (worldEntity is Unit unitEntity && unitRenderersById.TryGetValue(unitEntity.Id, out UnitRenderer unitRenderer)) { spellVisualController.HandleRendererDetach(unitRenderer); selectionCircleController.HandleRendererDetach(unitRenderer); foreach (IUnitRendererHandler handler in unitRendererHandlers) { handler.HandleUnitRendererDetach(unitRenderer); } unitRenderer.Deinitialize(); unitRenderersById.Remove(unitEntity.Id); unitRenderers.Remove(unitRenderer); GameObjectPool.Return(unitRenderer, unitRenderer.gameObject == null); } }
static int CreatePool(IntPtr L) { try { ToLua.CheckArgsCount(L, 5); ObjectPoolManager obj = (ObjectPoolManager)ToLua.CheckObject(L, 1, typeof(ObjectPoolManager)); string arg0 = ToLua.CheckString(L, 2); int arg1 = (int)LuaDLL.luaL_checknumber(L, 3); int arg2 = (int)LuaDLL.luaL_checknumber(L, 4); UnityEngine.GameObject arg3 = (UnityEngine.GameObject)ToLua.CheckUnityObject(L, 5, typeof(UnityEngine.GameObject)); GameObjectPool o = obj.CreatePool(arg0, arg1, arg2, arg3); ToLua.PushObject(L, o); return(1); } catch (Exception e) { return(LuaDLL.toluaL_exception(L, e)); } }
new void Start() { base.Start(); _machine.RegisterState(new Enemy_3_OutGroundState("out", this)); _machine.RegisterState(new Enemy_3_InGroundState("in", this)); _machine.ChangeState("in"); _hurtcontroller._HurtCallBack = new HurtCallBack(() => { GameObject temp2 = GameObjectPool.GetInstance().GetGameObject("主角攻击特效", transform.position + new Vector3(0, 1.5f, 0), Quaternion.identity); GameObjectPool.GetInstance().ReleaseGameObject("主角攻击特效", temp2, 0.5f); }); _hurtcontroller._DieCallBack = new DieCallBack(() => { GetComponent <Rigidbody2D>().gravityScale = 0; GetComponent <BoxCollider2D>().enabled = false; _anim.SetTrigger("die"); Destroy(gameObject, 2); }); }
IEnumerator IGameManager.Init() { m_Status = ManagerStatus.LOADING; GameObject ghostContainer = GameObject.Find("Ghosts"); if (ghostContainer == null) { ghostContainer = new GameObject("Ghosts"); } m_GhostCarPool = new GameObjectPool <GhostCar>(m_InitialCarPoolSize, ghostContainer.transform, m_GhostCarPrefab.gameObject); Debug.Log("Object Manager Started"); yield return(null); m_Status = ManagerStatus.STARTED; }
public override void Attack() { if( spawnPos.x == 0) { spawnPos += GameData.Instance.gamePlayManager .gameObjectPoolPosition.transform.position; } //원거리에서 공격할 수 있도록 구현. if(objPool == null) { objPool = new GameObjectPool( spawnPos.x, shotObj); } EnemyShotObj tempEnemyShot = null; if( !objPool.NextGameObject(out tempObj) ) { tempObj = Instantiate( shotObj, spawnPos, Quaternion.identity ) as GameObject; tempObj.name = shotObj.name + objPool.lastIndex; objPool.AddGameObject(tempObj); tempEnemyShot = tempObj.GetComponent<EnemyShotObj>(); tempEnemyShot.InitReturnPosition(spawnPos); } // position move tempObj.transform.position = firePosition.position; //속도 지정. tempVector2 = Vector2.right* -1 * fireSpeed; tempObj.rigidbody2D.velocity = tempVector2; //게임 오브젝트에 공격력을 담아 장애물 등과 충돌했을 때 데미지를 끼칠 수 있도록 한다. if(tempEnemyShot == null) { tempEnemyShot = tempObj.GetComponent<EnemyShotObj>(); } tempEnemyShot.InitShotObj( attackPower ); tempEnemyShot.TurnOnTrigger(); }
private GameObjectPool GetPool(GameObject prefab, string poolName) { ObjectPoolManager poolManager = ObjectPoolManager.Instance; Assert.IsNotNull(poolManager); GameObjectPool pool = poolManager.GetPool <GameObjectPool>(poolName); if (pool != null) { return(pool); } pool = new GameObjectPool(prefab, MaxTileCount * 2); poolManager.AddPool(poolName, pool); return(pool); }
void Awake() { scrollRect = gameObject.GetComponent <ScrollRect>(); content = scrollRect.content; displayRect = new Rect(0, 0, scrollRect.viewport.rect.width, scrollRect.viewport.rect.height); itemPool = content.gameObject.AddComponent <GameObjectPool>(); itemPool.target = itemTemplate.gameObject; itemTemplate.gameObject.SetActive(false); itemTemplate.pivot = new Vector2(0, 1); itemTemplate.anchorMin = new Vector2(0, 1); itemTemplate.anchorMax = new Vector2(0, 1); scrollRect.vertical = direction == Direction.Vertical; scrollRect.horizontal = direction == Direction.Horizontal; content.anchorMin = direction == Direction.Horizontal ? new Vector2(0, 0.5f) : new Vector2(0.5f, 1); content.anchorMax = direction == Direction.Horizontal ? new Vector2(0, 0.5f) : new Vector2(0.5f, 1); content.pivot = direction == Direction.Horizontal ? new Vector2(0, 0.5f) : new Vector2(0.5f, 1); ChangeAnchor(center, direction == Direction.Horizontal ? new Vector2(0, 0.5f) : new Vector2(0.5f, 1)); //center.anchoredPosition += new Vector2(0.5f * (center.parent as RectTransform).rect.width,0); //center.anchorMin = direction == Direction.Horizontal ? new Vector2(0, 0.5f) : new Vector2(0.5f, 1); //center.anchorMax = direction == Direction.Horizontal ? new Vector2(0, 0.5f) : new Vector2(0.5f, 1); scrollRect.onValueChanged.AddListener(ListenerMethod); EventTrigger et = gameObject.AddComponent <EventTrigger>(); EventTrigger.Entry entry = new EventTrigger.Entry(); entry.eventID = EventTriggerType.EndDrag; entry.callback.AddListener(OnDragEndHandle); et.triggers.Add(entry); entry = new EventTrigger.Entry(); entry.eventID = EventTriggerType.BeginDrag; entry.callback.AddListener(OnDragHandle); et.triggers.Add(entry); displayRect.x = 0; displayRect.y = 0; scrollRect.verticalNormalizedPosition = 1; scrollRect.horizontalNormalizedPosition = 0; }
public static IPool CreatePrefabPool(object reference, int startSize = 0) { IPool pool; if (reference is Component) { var component = (Component)reference; Transform poolTransform = null; if (ApplicationUtility.IsPlaying) { poolTransform = Transform.AddChild(component.name + " Pool"); } var poolType = typeof(ComponentPool <>).MakeGenericType(reference.GetType()); pool = (IPool)Activator.CreateInstance(poolType, reference, poolTransform, startSize); } else if (reference is GameObject) { var gameObject = (GameObject)reference; Transform poolTransform = null; if (ApplicationUtility.IsPlaying) { poolTransform = Transform.AddChild(gameObject.name + " Pool"); } pool = new GameObjectPool(gameObject, poolTransform, startSize); } else if (reference is ScriptableObject) { var poolType = typeof(ScriptablePool <>).MakeGenericType(reference.GetType()); pool = (IPool)Activator.CreateInstance(poolType, reference, startSize); } else { var poolType = typeof(Pool <>).MakeGenericType(reference.GetType()); pool = (IPool)Activator.CreateInstance(poolType, reference, startSize); } return(pool); }
/// <summary> /// 复写当资源加载完毕后的回调函数 /// 需要额外执行创建对象池的功能 /// </summary> /// <param name="_key"></param> /// <param name="_path"></param> /// <param name="_asset"></param> protected override void OnAssetLoaded(Tkey _key, string _path, GameObject _asset) { base.OnAssetLoaded(_key, _path, _asset); try { var poolSize = defaultPoolCount; if (poolSize < 0) { poolSize = GetOverridePoolCount(_key); } if (copyAssets) { var newAsset = Object.Instantiate(_asset, copyedAssetsRoot.transform); OnAssetsCopyed(ref newAsset); newAsset.SetActive(false); var pool = new GameObjectPool(newAsset, poolSize, false, dontReparent, _hideInEditor: shouldHidePools) { AutoExpand = autoExpand, AutoExpandCount = autoExpandCount }; pool.MoveToScene(resourcesScene); pooling.Add(_key, pool); } else { var pool = new GameObjectPool(_asset, poolSize, false, dontReparent, _hideInEditor: shouldHidePools) { AutoExpand = autoExpand, AutoExpandCount = autoExpandCount }; pool.MoveToScene(resourcesScene); pooling.Add(_key, pool); } } catch (Exception _e) { Debug.LogException(_e); Debug.LogError($"创建物体时发生错误,资源不存在。类型{this.GetType().ToString()}, ID{_key}, 资源路径{_path}"); } }
/// <summary> /// Create the underwater effect. Keep it alive as long as it's active /// </summary> /// <param name="rAnimator">Mecanim animator this swimmer is tied to</param> /// <param name="rBone">Bone the effect is to play from</param> public void CreateUnderwaterEffect(Animator rAnimator, HumanBodyBones rBone) { if (mUnderwaterCore == null) { if (UnderwaterPrefab != null) { //GameObject lUnderwater = GameObject.Instantiate(Resources.Load(mUnderwaterPath)) as GameObject; GameObject lUnderwater = GameObjectPool.Allocate(UnderwaterPrefab); if (lUnderwater != null) { Vector3 lPosition = Vector3.zero; if (rAnimator != null) { Transform lBone = rAnimator.GetBoneTransform(rBone); if (lBone != null) { lPosition = lBone.position; } } mUnderwaterCore = lUnderwater.GetComponent <ParticleCore>(); mUnderwaterCore.Prefab = UnderwaterPrefab; mUnderwaterCore.OnReleasedEvent = OnUnderwaterReleased; mUnderwaterCore.Transform.parent = mActorController._Transform; mUnderwaterCore.Transform.position = lPosition; } } } else { mUnderwaterCore.Age = 0f; if (rAnimator != null) { Transform lBone = rAnimator.GetBoneTransform(rBone); if (lBone != null) { mUnderwaterCore.Transform.position = lBone.position; } } } }
public void Restart() { spawnTarget = 0; levelID = levelHelper.levelID; if (panelRestart.activeSelf) { StartCoroutine(WaitClosedUI(panelRestart)); } else if (panelWin.activeSelf) { StartCoroutine(WaitClosedUI(panelWin)); } isPlayGame = false; folow = false; if (targetSpawned.Count != 0) { for (int i = 0; i < targetSpawned.Count; i++) { if (targetSpawned[i].gameObject != null) { GameObjectPool.Unspawn(targetSpawned[i].gameObject); } } targetSpawned.Clear(); targets.Clear(); } if (dravTutorial) { StartCoroutine(WaitDrawUI(panelTutorial)); } else { ButtonStartGame(); } squareTargets = 0; delayBetweenGateAndSpawn = false; }
public static void DoDestroy(GameObject go, bool checkIngore = true) { if (!Application.isPlaying) { go.SetActive(false); return; } GameObjectPoolObject poolObject = go.GetComponent <GameObjectPoolObject>(); if (poolObject == null) { //GameObject.Destroy(this.gameObject); go.SetActive(false); return; } if (poolObject.IsInPool) { go.SetActive(false); return; } //GameObjectPoolObject提供了无视这次销毁操作的接口,用于某些特殊的特效做延迟销毁 if (checkIngore && poolObject.m_onIngoreDestroy != null && poolObject.m_onIngoreDestroy()) { return; } #if !ART_DEBUG if (Main.instance != null) { GameObjectPool.GetPool(GameObjectPool.enPool.Fx).Put(go); } else { go.SetActive(false); } #else go.SetActive(false); #endif }
private void setupObjectPool(int capacity) { string prefabName = "LODSystem." + base.name; if (Singleton <GameObjectPoolManager> .Instance.TryGetPool(prefabName, out pool)) { return; } GameObject gameObject = new GameObject(prefabName); gameObject.AddComponent <LODRequest>(); foreach (LODWeightingData ruleDatum in data.RuleData) { ruleDatum.InstantiateRequest(gameObject); } pool = Singleton <GameObjectPoolManager> .Instance.AddPoolForObject(gameObject, ScriptableObject.CreateInstance <GrowPool>()); pool.Capacity = capacity; gameObject.transform.SetParent(pool.transform, worldPositionStays: false); }
void OnEnable() { if (pointPool == null) { pointPool = new GameObjectPool(pointPrefab, dotCount, false); } points = new List <Vector2>(); for (int i = 0; i < dotCount; i++) { points.Add(Vector2.zero); } for (int i = 0; i < dotCount; i++) { GameObject temp = pointPool.GetObject(); temp.SetActive(true); temp.transform.parent = transform; } }
private void CircleLaunch() { var angle = Time.time * TurnSpeed % 360; var dir = new Vector3(Mathf.Cos(angle), 1, Mathf.Sin(angle)); _Launcher.localPosition = dir; _Launcher.rotation = Quaternion.LookRotation(dir); if (!_LaunchCounter.Completed) { return; } _LaunchCounter.Recount(); Vector3 force = Trans.localToWorldMatrix * dir.normalized * LaunchSpeed; var saucer = GameObjectPool.Get <FlyingSaucer>("flyingSaucer"); saucer.transform.position = _Launcher.position; saucer.Launch(force); }
public IEnumerable <GameObject> SpawnUnits(IEnumerable <GameObject> prefabs, ConflictLocation conflict) { Vector2 originalPos = conflict.center; foreach (var prefab in prefabs) { Vector2 position; if (!FindPositionForUnit(prefab, conflict, out position)) { continue; } GameObjectPool goPool = GameObjectPool.Get(prefab); GameObject instance = goPool.Take(); SetupUnit(instance, position, goPool, originalPos); yield return(instance); } }
// Use this for initialization protected override void OnStart() { //base.OnStart(); int num = 0; m_projectile_Pool = new GameObjectPool <GameObject>(10, () => { ++num; GameObject obj = Instantiate(m_projectile) as GameObject; obj.name = "bullet" + num; obj.transform.parent = m_bulletPool.transform; return(obj); }); SoundManager.Instance.PlayBGM(SoundManager.BGM_CLIP.BGM_01); m_projectileList = new List <Projectile>(); m_invincibleEffect.SetActive(false); m_animation = GetComponent <Animation>(); Invoke("OnShoot", 3f); m_power = 1; }
private void InitBaseSys() { //gameObject.AddComponentEx<AppConfig>(); TimerManager.CreateInstance(); InputTimerManager.GetInstance(); DownloadManager.CreateInstance(); WindowRegister.CreateInstance(); //HUIManager.CreateInstance (); //ActorObjManager.CreateInstance (); GameObjectPool.CreateInstance(); TableProtoManager.Instance.PreLoadTableData(); //UISpriteManager.CreateInstance (); //SDKManager.CreateInstance (); //UserManager.CreateInstance (); TimeUtils.CurUnixTime = TimeUtils.ToUtcSeconds(DateTime.Now); //RestManager.CreateInstance(); }
public void Initialize(AbstractFightMap fightMap, Material material, uint renderLayerMask) { //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Expected O, but got Unknown //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Expected O, but got Unknown m_fightMap = fightMap; GameObject val = new GameObject("", new Type[1] { typeof(SpriteRenderer) }); SpriteRenderer component = val.GetComponent <SpriteRenderer>(); component.set_sharedMaterial(material); component.set_renderingLayerMask(renderLayerMask); val.SetActive(false); Object.DontDestroyOnLoad(val); m_pool = new GameObjectPool(val, 4); m_prefab = val; }
void Start() { m_Instance = this; if (GameObject.FindObjectsOfType(this.GetType()).Length > 1) { Debug.LogError("Can't have more than one Object Pool Manager in a scene."); } for (int i = 0; i < ObjectPoolStartAmounts.Count; ++i) { m_ObjectPoolDictionary.Add(ObjectPoolNames[i], null); m_ObjectPoolDictionary[ObjectPoolNames[i]] = new GameObjectPool(); for (int j = 0; j < ObjectsToPool[i].InnerList.Count; ++j) { m_ObjectPoolDictionary[ObjectPoolNames[i]].AddSource(ObjectsToPool[i].InnerList[j], ObjectPoolStartAmounts[i].InnerList[j]); } } }
private void Start() { gameObjectPoolsDict = new Dictionary <FoodEnum, GameObjectPool>(); GameObjectPool newPool1 = gameObject.AddComponent <GameObjectPool>(); newPool1.PoolGameObject = Resources.Load <GameObject>("Prefabs/Meat"); gameObjectPoolsDict.Add(FoodEnum.Meat, newPool1); GameObjectPool newPool2 = gameObject.AddComponent <GameObjectPool>(); newPool2.PoolGameObject = Resources.Load <GameObject>("Prefabs/Bread"); gameObjectPoolsDict.Add(FoodEnum.Bread, newPool2); GameObjectPool newPool3 = gameObject.AddComponent <GameObjectPool>(); newPool3.PoolGameObject = Resources.Load <GameObject>("Prefabs/Lettuce"); gameObjectPoolsDict.Add(FoodEnum.Lettuce, newPool3); GameObjectPool newPool4 = gameObject.AddComponent <GameObjectPool>(); newPool4.PoolGameObject = Resources.Load <GameObject>("Prefabs/Tomato"); gameObjectPoolsDict.Add(FoodEnum.Tomato, newPool4); }
Application.LogCallback onLogMessageReceived( GameObjectPool <VerticalLayoutLogEntry> pool, List <string> resultsTo ) { return((message, stackTrace, type) => { foreach (var instance in current) { ASync.OnMainThread(() => { foreach (var e in createEntries( new LogEntry(message, type), pool, resultsTo, instance.view.lineWidth )) { instance.dynamicVerticalLayout.appendDataIntoLayoutData(e); } }); } }); }
public void PlayRadialBlur(float strength, Transform t, float duration, Vector3 offset, float beginSmooth, float endSmooth) { GameObject go = GameObjectPool.GetPool(GameObjectPool.enPool.Fx).GetImmediately("fx_camera_blur_internal", false); CameraFx cameraFx = go.GetComponent <CameraFx>(); CameraAni cameraAni = cameraFx.m_anis[0]; cameraAni.m_endFloat = strength; cameraAni.m_beginDuration = beginSmooth; cameraAni.m_endDuration = endSmooth; RadialBlur blur = go.GetComponent <RadialBlur>(); blur.target = t; blur.offset = offset; go.SetActive(true); FxDestroy.Add(go, duration); }
private void OnClientSpellFailed(SpellCastResult castResult) { if (!settings.AllowRepeating) { foreach (var item in activeErrors) { if (item.CastResult == castResult) { return; } } } errorAppearSound?.Play(); ActionErrorItem newError = GameObjectPool.Take(errorItemPrototype, errorContainer.position, errorContainer.rotation, errorContainer); newError.SetErrorText(castResult); newError.RectTransform.SetAsFirstSibling(); activeErrors.Add(newError); }
// Use this for initialization void Start() { BulletPool = PoolManager.Instance.CreatePool("BulletPool", Resources.Load("Prefabs/Bullets/PlayerBullet") as GameObject, 20, true); EventManager.Instance.AddListener <ShieldPowerEvent> (OnShieldPowerEvent); EventManager.Instance.AddListener <BulletBoostPowerEvent> (OnBulletBoostEvent); EventManager.Instance.AddListener <SpeedBoostPowerEvent> (OnSpeedBoostPowerEvent); EventManager.Instance.AddListener <SpreadGunPowerEvent> (OnSpreadGunPowerEvent); EventManager.Instance.AddListener <ShadowAircraftPowerEvent> (OnShadowAircraftPowerEvent); EventManager.Instance.AddListener <LaserPowerEvent> (OnLaserPowerEvent); // save shooting delays for (int i = 0; i < Guns.Length; i++) { float delay = Guns [i].ShootingDelay; _TmpShootingDelays.Add(delay); } _Collider = GetComponent <Collider2D> (); }
public override GameObject GetObjectToReplace(GameObjectPool pool, List <GameObject> activeInstances, Stack <GameObject> inactiveInstances) { float num = float.MaxValue; GameObject gameObject = null; for (int i = 0; i < activeInstances.Count; i++) { float num2 = CalculateDistanceSquared(activeInstances[i].transform); if (num2 < num) { num = num2; gameObject = activeInstances[i]; } } if (gameObject != null) { gameObject.SendMessage("OnStolenFromPool", SendMessageOptions.DontRequireReceiver); } return(gameObject); }
protected override void OnStart() { m_player = GameObject.FindGameObjectWithTag("Player").GetComponent <PlayerController>(); m_monsterPool = new GameObjectPool <MonsterController>(20, () => { var obj = Instantiate(m_monsterPrefab) as GameObject; //여기서 몬스터를 생성하고 액티브를 끄지않는다. 몬스터컨트롤러에서 액티브를 꺼야함. obj.transform.SetParent(transform); obj.transform.localPosition = Vector3.zero; obj.transform.localRotation = Quaternion.identity; obj.transform.localScale = Vector3.one; var mon = obj.GetComponent <MonsterController>(); mon.InitMonster(m_player); return(mon); }); InvokeRepeating("CreateMonsters", 3f, m_spawnInterval / m_spawnTimeScale); }
public void Construct(List <UnitData> units) { this.behaviourPool = MonoBehaviourPool <BehaviourView> .Factory( this.behaviourPrefab, this.behaviourContainer); this.spellbookSlotPool = MonoBehaviourPool <SpellbookSlot> .Factory( this.spellbookSlotPrefab, this.spellbookSlotContainer); this.propertyRowPool = MonoBehaviourPool <CharacterInfoRow> .Factory( this.propertyRowPrefab, this.propertyRowContainer); this.attributeRowPool = MonoBehaviourPool <BestiaryAttributeRow> .Factory( this.attributeRowPrefab, this.attributeRowContainer); this.propertyRowSeparatorPool = GameObjectPool.Factory( this.propertyRowSeparatorPrefab, this.propertyRowContainer); var grouped = units.OrderBy(u => u.Environment.Index).GroupBy(u => u.Environment.Id); foreach (var group in grouped) { Instantiate(this.unitRowTitlePrefab, this.unitRowContainer) .ChangeTitle(I18N.Instance.Get(group.First().Environment.NameKey)); foreach (var unit in group.OrderBy(u => u.NameKey)) { var unitRow = Instantiate(this.unitRowPrefab, this.unitRowContainer); unitRow.Clicked += OnUnitRowClicked; unitRow.Construct(unit); } } var firstRow = this.unitRowContainer.GetComponentsInChildren <BestiaryUnitRow>().FirstOrDefault(); if (firstRow == null) { return; } OnUnitRowClicked(firstRow); }
void Awake() { if (Instance != null) { Debug.LogError("重复创建GameApp!"); GameObject.Destroy(gameObject); return; } Instance = this; DontDestroyOnLoad(gameObject); GameObjectPool.Startup(); UserName = ""; Platform = Application.platform.ToString(); DeviceUniqueIdentifier = SystemInfo.deviceUniqueIdentifier; DeviceModel = SystemInfo.deviceModel; DeviceTypeStr = SystemInfo.deviceType.ToString(); Debug.Log("SystemInfo.deviceModel: " + SystemInfo.deviceModel); Debug.Log("SystemInfo.deviceName: " + SystemInfo.deviceName); Debug.Log("SystemInfo.deviceType: " + SystemInfo.deviceType.ToString()); Debug.Log("SystemInfo.graphicsDeviceID: " + SystemInfo.graphicsDeviceID); Debug.Log("SystemInfo.graphicsDeviceName: " + SystemInfo.graphicsDeviceName); Debug.Log("SystemInfo.graphicsDeviceType: " + SystemInfo.graphicsDeviceType.ToString()); Debug.Log("SystemInfo.graphicsDeviceVendor: " + SystemInfo.graphicsDeviceVendor); Debug.Log("SystemInfo.graphicsDeviceVendorID: " + SystemInfo.graphicsDeviceVendorID); Debug.Log("SystemInfo.graphicsDeviceVersion: " + SystemInfo.graphicsDeviceVersion); ScreenWidth = Screen.width; ScreenHeight = Screen.height; // Net.Instance.HeadFormater = new CustomHeadFormater(); ExcelLoader.Init(); SkillEventRegister.Initialize(); if (directGame) { SceneSystem.Instance.ChangeScene(SceneSystem.roomScnID); return; } SceneSystem.Instance.ChangeScene(SceneSystem.loginScnID); }
public void Connect(GameModel gameModel, List <GuestParams> guestList, GameObjectPool pool, GlobalParams globalParams, CommonAssets commonAssets, Camera camera1, Transform bubbleContainer, Transform minigameContainer, PlayerController playerController) { _gameModel = gameModel; _pool = pool; _globalParams = globalParams; _commonAssets = commonAssets; _camera = camera1; _bubbleContainer = bubbleContainer; _minigameContainer = minigameContainer; _playerController = playerController; foreach (var guestParams in guestList) { CreateGuest(guestParams); } EventManager.OnClueGet += AddClue; }
void Start() { if (isServer) { m_Instance = this; if (GameObject.FindGameObjectsWithTag(ConstParams.ObjectPoolManager).Length > 1) { Debug.LogError("Can't have more than one Object Pool Manager in a scene."); } for(int i = 0; i < ObjectPoolStartAmounts.Count; ++i) { m_ObjectPoolDictionary.Add(ObjectPoolNames[i], null); for (int j = 0; j < ObjectsToPool[i].InnerList.Count; ++j) { m_ObjectPoolDictionary[ObjectPoolNames[i]] = new GameObjectPool(ObjectsToPool[i].InnerList[j], ObjectPoolStartAmounts[i].InnerList[j]); } } } }
void Start() { bulletPrefab = Resources.Load<GameObject>("Prefabs/Bullet"); ani = GetComponent<Animator>(); sprs = transform.FindChild("Graphic").GetComponentsInChildren<SpriteRenderer>(); bulletPool = new GameObjectPool<GameObject>(bulletCount, bulletPrefab, (GameObject obj) => { GameObject clone = GameObject.Instantiate(bulletPrefab); clone.SetActive(false); return clone; }); FireButton.onClick.AddListener(OnFireButton); ChangeButton.onClick.AddListener(OnChangeButton); ChangeColor(GameLogic.Instance.giveColorList[ColorIdx]); StartCoroutine(CannonProcess()); }
void OnEnable () { Instance = this; m_containerObject = new GameObject("GameObjectPool"); m_poolOfObjects = new List<GameObject>[Prefabs.Length]; //We build up the pools int prefabIndex = 0; foreach (PoolItem poolItem in Prefabs) { Debug.Assert(poolItem.Prefab != null, "You need to specify a prefab / gameobject to initate the pool with, check element: " + prefabIndex.ToString()); Debug.Assert(poolItem.PoolSize > 0, "You tried to initiate a pool with size 0 with object type: " + poolItem.Prefab.name); m_poolOfObjects[prefabIndex] = new List<GameObject>(); for (int n = 0; n < poolItem.PoolSize; ++n) { GameObject newObj = Instantiate(poolItem.Prefab) as GameObject; newObj.name = poolItem.Prefab.name; AddToPool(newObj); } ++prefabIndex; } }
void Start() { m_Instance = this; if (GameObject.FindObjectsOfType(this.GetType()).Length > 1) { Debug.LogError("Can't have more than one Object Pool Manager in a scene."); } for(int i = 0; i < ObjectPoolStartAmounts.Count; ++i) { m_ObjectPoolDictionary.Add(ObjectPoolNames[i], null); m_ObjectPoolDictionary[ObjectPoolNames[i]] = new GameObjectPool(); for (int j = 0; j < ObjectsToPool[i].InnerList.Count; ++j) { m_ObjectPoolDictionary[ObjectPoolNames[i]].AddSource(ObjectsToPool[i].InnerList[j], ObjectPoolStartAmounts[i].InnerList[j]); } } }
public void InitObjectPools() { poolOlli = GameObjectPool.GetPool("Olli"); }
void Awake() { _instance = this; }
void Start() { m_iconPool = new GameObjectPool(livesIcon, 10, false, transform, true); }
// Use this for initialization void Start() { cannons = GameObject.Find ("CannonObjectPool").GetComponent<GameObjectPool> (); }
/// <summary> /// Adds a pool. You only need to do this /// if you want to set a specific initial size or /// do intial instantiates up front. /// </summary> /// <param name="targetPreFabrication">Target pre fabrication.</param> /// <param name="initialSize">Initial size.</param> /// <typeparam name="T">The 1st type parameter.</typeparam> public void AddPool(GameObject targetPreFabrication, int initialSize) { GameObjectPool pool = new GameObjectPool(targetPreFabrication, initialSize); pools.Add(targetPreFabrication, pool); }
// 게임 오브젝트 풀 초기화. void InitGameObjectPool() { spawnPos += GameData.Instance.gamePlayManager .gameObjectPoolPosition.transform.position; //원거리에서 공격할 수 있도록 구현. objPool = new GameObjectPool( spawnPos.x, tempObj); // 발사 오브젝트 생성. for(int i=0;i<20;++i) { shotObjScript = null; GameObject makeObj = Instantiate( fireObj, spawnPos, Quaternion.Euler(Vector3.up * 90) ) as GameObject; makeObj.name = makeObj.name + i; objPool.AddGameObject(makeObj); shotObjScript = makeObj.GetComponent<ShotObj>(); shotObjScript.InitReturnPosition(spawnPos); } }
/// <summary> /// Добавляет пул и размещает его в билиотеке по заданному ключу. /// </summary> /// <param name="poolKey"> Ключ-строка. </param> /// <param name="pool"> Пул. </param> public void SetPool(string poolKey, GameObjectPool pool) { pools[poolKey] = pool; }
void Awake() { Pool = new GameObjectPool( Prefab, 0, transform ); }
/* * Function: initObjectPool * * Parameters: none * * Returns: void * * Initializes the <terrainObjectPool> with new instances of <terrainObject>, which is the GameObject prefab used to visualize terrain objects * in the worldspace. */ private void initObjectPool() { // Destroy any previous objects List<GameObject> children = new List<GameObject> (); foreach(Transform child in terrainObjectHolder.transform) { children.Add(child.gameObject); } children.ForEach (child => Destroy(child)); // Initialize terrain mesh object pool terrainObjectPool = new GameObjectPool (terrainObject, unassigned_go_name, GameController.RendererSettings.terrain_pool_size, terrainObjectHolder); }
public void Start() { if (bullet != null && m_bulletPool == null) m_bulletPool = new GameObjectPool(bullet, 5, false); // One more bullet on screen allowed than original Asteroids to account for wide screen. }
protected void Awake() { _chunkPool = GameObject.Find("ChunkPool"). GetComponent<GameObjectPool>(); _screenMeshes = new Dictionary<XY, GameObject>(); }
// Use this for initialization void Awake() { Assert.IsNull(Instance, "More than 1 instance of AudioPool detected. ONLY HAVE 1 IN THE SCENE PLZ"); Instance = this; DefaultSettings = new AudioClipSettings(); // Set up the object pool of audio sources m_AudioSources = new GameObjectPool(1, m_emptyPrefab, this.gameObject); }
void CreateGameObject(GameObject targetObj, int amount, Transform parent, Vector3 localScale=default(Vector3)) { // 게임 오브젝트 풀 생성. GameObjectPool tempGameObjectPool = new GameObjectPool(gameObjectPoolPosition.transform.position.x, targetObj); for (int j=0; j<amount; j++) { // 게임 오브젝트 생성. GameObject tempObj = Instantiate( targetObj, gameObjectPoolPosition.position, Quaternion.identity ) as GameObject; tempObj.name = targetObj.name + j; tempObj.transform.parent = parent; if (localScale != Vector3.zero) { tempObj.transform.localScale = localScale; } // 게임 오브젝트를 게임 오브젝트 풀에 등록. tempGameObjectPool.AddGameObject(tempObj); } gameObjectPools.Add(targetObj.name, tempGameObjectPool); }
public GameObjectPool AddPool(GameObjectPool pool) { return pools[pool.prefab] = pool; }
void Awake() { weaponPool = new GameObjectPool(projectile, maximumSize, initialSize, transform); impactPool = new GameObjectPool(impact, -1, initialSize / 2, transform); WeaponManager.Register(this); weapon = projectile.GetComponent<IWeapon>(); }