public void HideObject(PooledObject obj) { obj.transform.position = transform.position; obj.transform.rotation = transform.rotation; obj.Reset(); obj.gameObject.SetActive(false); }
public static PooledObject Retain(PooledObject prefab) { if (_instance != null) return _instance.retain(prefab); Debug.LogWarning("No ObjectPools instance exists, cannot retain " + prefab); return instantiate(prefab); }
public PooledObject Alloc(Vector3 position) { Assert(IsPrefab); PooledObject result; if (next != null) { // RECYCLE INSTANCE result = next; next = result.next; result.next = null; result.transform.position = position; result.gameObject.SetActive(true); } else { // CREATE NEW INSTANCE result = Dup(this, position); result.prefab = this; } // RE-INIT INSTANCE result.Init(); return result; }
public static void Release(PooledObject toRelease) { if (_instance != null) _instance.release(toRelease); else Debug.LogWarning("No ObjectPools instance exists, cannot release " + toRelease); }
public static void ReleaseObject(PooledObject obj) { CleanUp(obj); lock (Available) { InUsed.Remove(obj); Available.Add(obj); } }
public static void ReleaseObject(PooledObject po) { CleanUp(po); lock (available) { available.Add(po); inUse.Remove(po); } }
public bool restore(PooledObject iObject) { if (!_objectList.Contains (iObject)) { Debug.LogWarning ("Error!: ["+iObject+"] is not not member of ["+_tag+"]!"); return false; } iObject.transform.parent = _transform; iObject._isFree = true; iObject._object.SetActive (false); return true; }
/// <summary> /// Adds an object to the pool /// </summary> /// <param name="obj"></param> public void Add(GameObject obj) { if (this.pooledObjects.Count >= maxCapacity) { throw new MaxCapacityReachedException("Object pool has reached the capacity of " + this.maxCapacity + ". Cannot add object (" + obj.name + ") to pool."); } obj.SetActive(false); var po = new PooledObject<GameObject>(obj); GameObject.DontDestroyOnLoad(obj); // We will take care of cleaning these up ourselves this.pooledObjects.Add(po); }
public static PooledObject GetObject() { lock (Available) { PooledObject obj; if (Available.Count == 0) { obj = new PooledObject(); InUsed.Add(obj); return obj; } obj = Available[0]; InUsed.Add(obj); Available.RemoveAt(0); return obj; } }
private void release(PooledObject toRelease) { int poolId = toRelease.PoolId; if (poolId < 0 || poolId >= _pools.Length) { Debug.LogWarning("No pool found with id " + poolId + ", specified on object " + toRelease); } else { if (returnObject(_pools[poolId], toRelease)) return; } Destroy(toRelease.gameObject); }
public void Release() { Deinit(); if (prefab != null) { // DEACTIVATE AND PREPEND TO PREFAB'S FREELIST gameObject.SetActive(false); next = prefab.next; prefab.next = this; } else if (gameObject) { // THIS OBJECT WAS NOT DYNAMICALLY CREATED Destroy(gameObject); } }
public static PooledObject GetObject() { lock (available) { if (available.Count != 0) { PooledObject po = available[0]; inUse.Add(po); available.RemoveAt(0); return po; } else { PooledObject po = new PooledObject(); inUse.Add(po); return po; } } }
public static ObjectPool GetPool(PooledObject prefab) { GameObject obj; ObjectPool pool; if(Application.isEditor) { obj = GameObject.Find(prefab.name + " Pool"); if(obj) { pool = obj.GetComponent<ObjectPool>(); if(pool) return pool; } } obj = new GameObject(prefab.name + " Pool"); DontDestroyOnLoad(obj); pool = obj.AddComponent<ObjectPool>(); pool._prefab = prefab; return pool; }
private PooledObject retain(PooledObject prefab) { int poolId = prefab.PoolId; if (poolId < 0 || poolId >= _pools.Length) { Debug.LogWarning("No pool found with id " + poolId + ", specified on prefab " + prefab); } else { List<PooledObject> pool = _pools[prefab.PoolId]; if (pool.Count > 0) { PooledObject instance = pool.Pop(); instance.gameObject.SetActive(true); return instance; } } return instantiate(prefab); }
internal override void Initialize(int particleIndex, ParticleComponent <TextParticle> parent, PooledObject <TextParticle> newParticle, Action <TextParticle> intializer, Action <float, TextParticle> onTick) { base.Initialize(particleIndex, parent, newParticle, intializer, onTick); camera = parent.Entity.Game.EngineComponents.Get <Renderer2d>().GameCamera; Position = parent.Entity.Body.Position; }
public static void ReturnPooledObject(PooledObject obj) { Instance.objectPools.ReturnObject(obj); }
/// <summary> /// Used when an object is going out of the pool. /// </summary> /// <param name="pooledObject">The pooled object which has to be validated.</param> internal static PooledObjectValidationContext Outbound(PooledObject pooledObject) => new PooledObjectValidationContext { PooledObject = pooledObject, Direction = PooledObjectDirection.Outbound };
void Start() { pooledObject = GetComponent <PooledObject>(); player = GameObject.FindGameObjectWithTag("Player"); rb = GetComponent <Rigidbody>(); }
void Initialize() { #if UNITY_EDITOR // Recreate the log file var f = File.Create("PoolManagerLog.txt"); f.Close(); #else log = new List <string>(); #endif if (logging) { int objectCount = 0; foreach (var cat in m_Categories) { objectCount += cat.m_Pools.Length; } Log(m_Categories.Length + " categories with " + objectCount + " objects in total."); Log("Startup caching is " + (startupCaching ? "enabled." : "disabled.")); } active = new List <GameObject>(); isInstantiating = true; Stopwatch sw = new Stopwatch(); sw.Start(); // Initialize pools foreach (var cat in m_Categories) { foreach (var pool in cat.m_Pools) { if (!pool.pooledObject) { continue; } // Instantiate pooled objects pool.pooledObjects = new List <PooledObject>(); // Only initialize "Allow steal" pools if startup caching is disabled if (!pool.allowSteal && !startupCaching) { continue; } for (int i = 0; i < pool.poolSize; ++i) { PooledObject po = new PooledObject(); po.go = Instantiate(pool.pooledObject); po.go.transform.SetParent(transform); po.go.SetActive(false); pool.pooledObjects.Add(po); } } } isInstantiating = false; sw.Stop(); Debug.Log("PoolManager instantiated in " + (float)sw.ElapsedMilliseconds * 0.001f + " s"); if (logging) { Log(""); Log("Objects instantiated in " + (float)sw.ElapsedMilliseconds * 0.001f + " s"); Log(""); Log("------------------------------------------------------------"); Log(""); } if (AfterInitialization != null) { AfterInitialization(); } }
public static void CleanUp(PooledObject obj) { obj.TempData = null; }
public ObjectPoolItem(PooledObject pooledObject) { this.pooledObject = pooledObject; }
public void AddObject(PooledObject pooledObject) { pooledObject.gameObject.SetActive(false); availableObjects.Add(pooledObject); //Object.Destroy(pooledObject.gameObject); }
void Start() { pool = GetComponent <PooledObject>(); rb = GetComponentsInChildren <Rigidbody>(); lifetimeStart = lifetime; }
public void RefillObject(PooledObject pooledObject) { m_freeObject.Add(pooledObject); }
void Awake() { spriteRenderer = GetComponent <SpriteRenderer>(); pooled = PooledObject.Get(gameObject); }
// Use this for initialization void Start() { rb = GetComponent <Rigidbody2D>(); pool = GetComponent <PooledObject>(); timer = lifetime; }
void Start() { pooledObject = GetComponent <PooledObject>(); //guns = GameObject.FindGameObjectWithTag("Player").GetComponent<GunManager>(); }
/// <summary> /// Affers a pooled memory chunk to this stream. /// </summary> /// <param name="pooledBytes"></param> /// <param name="offset"></param> /// <param name="length"></param> public ChunkedBuffer OfferChunk(PooledObject<byte[]> pooledObject, int offset, int count) { ValidateBuffer(); if (pooledObject == null) { throw new ArgumentNullException("'data' cannot be null"); } if (pooledObject.State != PooledObjectState.USED) { throw new Exception("This pooled object is not active."); } if (pooledObject.Pool != pool) { throw new Exception("The given pooled object does not belong to ths pool that is assigned to this stream: " + pooledObject.Pool); } MemoryChunkNode chunk = new MemoryChunkNode() { pooledObject = pooledObject, pooledBytes = pooledObject.Value, offset = offset, count = count, next = null }; pooledObject.RefCount.Increment(); AppendChunk(chunk); return this; }
public void TestSharedModel() { string cbadfModelFile = "models/cb_adf.model"; var sampleData = CreateSampleCbAdfData(); using (var vw = new VowpalWabbit <DataString, DataStringADF>("--cb_adf --rank_all")) { foreach (DataString example in sampleData) { vw.Learn(example); } vw.SaveModel(cbadfModelFile); } // Get ground truth predictions var expectedPredictions = new List <DataStringADF[]>(); using (var vw = new VowpalWabbit <DataString, DataStringADF>(string.Format("-t -i {0}", cbadfModelFile))) { foreach (DataString example in sampleData) { expectedPredictions.Add(vw.Predict(example)); } } // Test synchronous VW instances using shared model using (var vwModel = new VowpalWabbitModel("-t", File.OpenRead(cbadfModelFile))) using (var vwShared1 = new VowpalWabbit <DataString, DataStringADF>(vwModel)) using (var vwShared2 = new VowpalWabbit <DataString, DataStringADF>(vwModel)) { for (int i = 0; i < sampleData.Length; i++) { DataStringADF[] actualPrediction = vwShared1.Predict(sampleData[i]); ReferenceEquals(expectedPredictions[i], actualPrediction); } } // Test concurrent VW instances using shared model and model pool using (var vwModel = new VowpalWabbitModel("-t", File.OpenRead(cbadfModelFile))) using (var vwPool = new ObjectPool <VowpalWabbit <DataString, DataStringADF> >(new VowpalWabbitFactory <DataString, DataStringADF>(vwModel))) { Parallel.For ( fromInclusive: 0, toExclusive: 20, parallelOptions: new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount * 2 }, body: i => { using (PooledObject <VowpalWabbit <DataString, DataStringADF> > vwObject = vwPool.Get()) { var actualPredictions = new List <DataStringADF[]>(); foreach (DataString example in sampleData) { actualPredictions.Add(vwObject.Value.Predict(example)); } Assert.AreEqual(expectedPredictions.Count, actualPredictions.Count); for (int j = 0; j < expectedPredictions.Count; j++) { ReferenceEquals(expectedPredictions[j], actualPredictions[j]); } } } ); } }
/// <summary> /// Parses a frame from a stream. /// </summary> /// <param name="stream"></param> /// <returns></returns> public static GdsFrame ParseFrame(Stream stream, ObjectPool <byte[]> bufferPool) { GdsFrame frame = new GdsFrame(bufferPool); BinaryReader reader = new BinaryReader(stream); uint frameDefinition = (uint)IPAddress.NetworkToHostOrder((int)reader.ReadUInt32()); if (!Enum.IsDefined(typeof(GdsFrameType), (byte)((frameDefinition & (uint)TypeMask) >> TypeShift))) { throw new ArgumentException("Invalid type: " + (GdsFrameType)(byte)((frameDefinition & (uint)TypeMask) >> TypeShift)); } frame.IsComplete = ((frameDefinition & IsCompleteMask) >> IsCompleteShift) == 1; frame.Type = (GdsFrameType)(byte)((frameDefinition & (uint)TypeMask) >> TypeShift); frame.StreamId = (frameDefinition & (uint)StreamIdMask) >> StreamIdShift; // parse the headers if (frame.Type == GdsFrameType.Full || frame.Type == GdsFrameType.HeadersOnly) { ushort headersDefinition = (ushort)IPAddress.NetworkToHostOrder((short)reader.ReadUInt16()); frame.AreHeadersCompressed = ((headersDefinition & (ushort)HeadersIsCompressedMask) >> HeadersIsCompressedShift) == 1; ushort count = (ushort)((headersDefinition & HeadersLengthMask) >> HeadersLengthShift); if (frame.AreHeadersCompressed) { long movePosition = stream.Position; using (DeflateStream compressedHeaderStream = new DeflateStream(stream, CompressionMode.Decompress, true)) { ReadHeadersFromStream(compressedHeaderStream, count, frame); movePosition += compressedHeaderStream.TotalIn; } stream.Position = movePosition; // we need to fix the position since the DeflateStream buffers the base stream } else { ReadHeadersFromStream(stream, count, frame); } } // read the body if (frame.Type == GdsFrameType.Full || frame.Type == GdsFrameType.BodyOnly) { uint length = (uint)IPAddress.NetworkToHostOrder((int)reader.ReadUInt32()); frame.Body = new ChunkedBuffer(bufferPool); PooledObject <byte[]> buffer = bufferPool.Borrow(); int count = 0; while ((count = reader.Read(buffer.Value, 0, buffer.Value.Length)) > 0) { frame.Body.OfferChunk(buffer, 0, count); buffer = bufferPool.Borrow(); } if (count < 1) { buffer.Return(); } if (frame.Body.AvailableBytesToRead != length) { throw new EndOfStreamException(); } } return(frame); }
public void Destroy(GameObject obj) { if (!obj.activeSelf) { return; // Don't re-destroy an object } PooledObject o = obj.GetComponent <PooledObject>(); if (o == null) { Object.Destroy(obj); return; // Don't try and pool non-poolables. } obj.SetActive(false); Boundary.WarpCount.Remove(obj); if (obj.GetComponent <Rigidbody2D>() != null) { obj.GetComponent <Rigidbody2D>().gravityScale = 0; } string ptag = o.Tag; Pool p = Pools.Find(x => x.tag == ptag); if (p == null) { Debug.LogWarning($"There is no pool for bullet {o.Tag}!"); return; } SpriteRenderer ospr = obj.GetComponent <SpriteRenderer>(); SpriteRenderer pspr = p.prefab.GetComponent <SpriteRenderer>(); if (ospr != null && pspr != null) { ospr.color = pspr.color; // reset color. } o.transform.localScale = p.prefab.transform.localScale; // Reset scale SimpleMovement sm = p.prefab.GetComponent <SimpleMovement>(); SimpleMovement osm = obj.GetComponent <SimpleMovement>(); if (sm != null && osm != null) { osm.UpdateAcceleration(sm.XAcceleration, sm.YAcceleration); } foreach (Component comp in obj.GetComponents(typeof(Component))) { if (p.prefab.GetComponent(comp.GetType()) == null) { Destroy(comp); } } if (o != null) { PoolDict[o.Tag].Enqueue(obj); } }
void SpawnObject(PooledObject prefabToSpawn) { SetSpawnedPooledObject(prefabToSpawn.GetPooledInstance <PooledObject>()); }
public GameObject GetPooledObject(string category, string type, bool autoActivate = true) { foreach (var cat in m_Categories) { if (cat.name == category) { // Attempt to find pool by name foreach (var pool in cat.m_Pools) { if (pool.name == type) { // Search for available pooled objects foreach (var po in pool.pooledObjects) { if (!po.go.activeInHierarchy) { // Available object found if (po.go && autoActivate) { po.go.SetActive(true); } po.setSpawnTime(Time.time); return(po.go); } } // No available pooled object found, check if we are allowed to expand the pool if (pool.allowExpand) { PooledObject po = new PooledObject(); po.go = Instantiate(pool.pooledObject); pool.pooledObjects.Add(po); if (po.go && autoActivate) { po.go.SetActive(true); } po.setSpawnTime(Time.time); return(po.go); } // No available pooled object found and we were not allowed to expand the pool, check if we are allowed to steal active objects if (pool.allowSteal) { // Find the oldest active object PooledObject po = pool.pooledObjects[0]; foreach (var p in pool.pooledObjects) { if (p.getSpawnTime() < po.getSpawnTime()) { po = p; } } /* * int index = 0; * for (int i = 0; i < pool.pooledObjects.Count; i++) * { * if (pool.pooledObjects[i].getSpawnTime() < pool.pooledObjects[index].getSpawnTime()) * index = i; * } * PooledObject po = pool.pooledObjects[index]; */ po.go.SetActive(false); if (po.go && autoActivate) { po.go.SetActive(true); } po.setSpawnTime(Time.time); return(po.go); } // No available pooled object found and we were not allowed to expand the pool or steal active objects return(null); } } // Pool not found return(null); } } // Category not found return(null); }
private static PooledObject instantiate(PooledObject prefab) { return Instantiate<PooledObject>(prefab); }
public void Start() { myHealth = GetComponent <BaseHealth>(); poolable = GetComponent <PooledObject>(); }
public void Enqueue(PooledObject obj, string tag) { obj.gameObject.SetActive(false); poolDictionary[tag].Enqueue(obj); }
public void Awake() { rb = GetComponent<Rigidbody>(); pooledObject = GetComponent<PooledObject>(); }
public void AddObject(PooledObject o) { o.gameObject.SetActive(false); o.gameObject.SetParent(transform, false); availableObject.Add(o); }
void Awake() { pooled = PooledObject.Get(gameObject); }
private static void CleanUp(PooledObject po) { po.TempData = null; }
internal virtual void Initialize(int particleIndex, ParticleComponent <T> parent, PooledObject <T> newParticle, Action <T> intializer, Action <float, T> onTick) { this.poolObject = newParticle; this.Parent = parent; TotalElapsedSeconds = 0; ParticleIndex = particleIndex; intializer((T)this); this.onTick = onTick; }
private void Awake() { m_pooled = GetComponent <PooledObject>(); m_sprite = GetComponent <SpriteRenderer>(); }
private bool returnObject(List<PooledObject> pool, PooledObject obj) { if (pool.Count < pool.Capacity) { obj.BroadcastMessage(POOL_RETURN_METHOD, SendMessageOptions.DontRequireReceiver); obj.transform.parent = null; obj.gameObject.SetActive(false); pool.Add(obj); return true; } return false; }
void IPoolNotificationHandler.OnAcquire() { Reinit(); PooledObject.Enable(gameObject); }
private static void CleanUp(PooledObject po) { po.TempData = null; }
void IPoolNotificationHandler.OnRelease() { PooledObject.Disable(gameObject); }
void ApplyDistanceOcclusion() { // Chunk center on the horizontal plane chunkCenter.x = transform.position.x + Chunk.Size / 2f; chunkCenter.z = transform.position.z + Chunk.Size / 2f; playerHPos.x = Game.Player.transform.position.x; playerHPos.z = Game.Player.transform.position.z; chunkDistance = Mathf.FloorToInt(Vector3.Distance(chunkCenter, playerHPos)); // initial load if (Game.ChunksLoaded < Config.StartChunksToLoad) { _renderer.enabled = false; _glassrenderer.enabled = false; outofrange = false; StartCoroutine(AwaitPlayer(() => { update = true; })); } // distance based occlusion if (chunkDistance > Config.MaxRenderDistance) { if (_renderer.enabled) { _renderer.enabled = false; } if (_glassrenderer.enabled) { _glassrenderer.enabled = false; } outofrange = true; } else if (chunkDistance <= Config.MaxRenderDistance) { if (!_renderer.enabled) { _renderer.enabled = true; } if (!_glassrenderer.enabled) { _glassrenderer.enabled = true; } outofrange = false; } // Chunk Deletion if (chunkDistance > Config.ChunkDeleteRadius * Chunk.Size) { World.Generator.RemoveResults(column.region); World.Columns.Remove(new World3(column.chunks[0].x, 0, column.chunks[0].z).GetHashCode()); if (column.spawns.Count > 0) { for (int i = column.spawns.Count - 1; i >= 0; i--) { PooledObject spawn = column.spawns[i]; spawn.ReturnToPool(); } column.spawns.Clear(); } for (int i = 0; i < column.chunks.Count; i++) { World.DestroyChunkAt(column.chunks[i]); } } }
void Start() { pooledObject = GetComponent <PooledObject>(); //moveScript = GameObject.FindGameObjectWithTag("Player").GetComponent<PlayerMovement>(); }
// Add an object to the pool (for now only destroys the object) public void AddObject(PooledObject obj) { // Set the object to inactive and add it to the list obj.gameObject.SetActive(false); availableObjects.Add(obj); }
public void AddObject(PooledObject obj) { obj.gameObject.SetActive(false); _availableObjects.Add(obj); }
public void AddObject(PooledObject obj) { obj.gameObject.SetActive(false); availableObjects.Add(obj); }
private void Push(PooledObject obj) { obj.gameObject.SetActive(false); PooledObjects[obj.index].Push(obj); }