/// <summary>
        /// Get poolable object from pool (pool will be created automatically or get from existing)
        /// </summary>
        /// <param name="parentTrans"></param>
        /// <returns></returns>
        public IPoolable GetNewObject(Transform parentTrans)
        {
            IPoolable poolable = GetNewObject();

            poolable.GetComponent <Transform>().SetParent(parentTrans, false);
            return(poolable);
        }
    private void SpawnPlayer(int i)
    {
        if (connected[i] == null)
        {
            return;
        }
        connected[i].spawned = true;
        Transform spawnPoint = playerSpawnPoint[i];
        IPoolable o          = PoolableFactory.Instance.Create <PlayerPoolable>(playerResourceId, spawnPoint.position, spawnPoint.rotation, null);
        Player    p          = (o as MonoBehaviour).gameObject.GetComponentInChildren <Player>();

        p.PlayerMaterial = playerMaterials[i];
        p.controller     = intToXboxController[i];

        if (!players.ContainsKey(i))
        {
            players.Add(i, p);
        }
        else
        {
            players[i] = p;
        }

        NotifyObservers(players.Values.ToArray());
    }
Exemplo n.º 3
0
    public static T Get <T>()
    {
        for (int i = 0; i < Instance.poolable.Count; i++)
        {
            if (Instance.poolable[i].GetType() == typeof(T))
            {
                IPoolable go = Instance.poolable[i];
                go.GetGameObject.SetActive(true);
                Instance.poolable.Remove(go);
                return((T)go);
            }
        }

        for (int i = 0; i < Instance.prefs.Length; i++)
        {
            T component = Instance.prefs[i].GetComponent <T>();
            if (component == null)
            {
                continue;
            }

            if (component.GetType() == typeof(T))
            {
                GameObject instance = Instantiate(Instance.prefs[i]);
                return(instance.GetComponent <T>());
            }
        }
        throw new System.Exception("There is no " + typeof(T));
    }
Exemplo n.º 4
0
        public T Get()
        {
            T obj;

            lock (this.objs)
            {
                if (this.objs.Count == 0)
                {
                    obj = null;
                }
                else
                {
                    obj = this.objs.First();
                    this.objs.Remove(obj);
                }
            }
            if (obj == null)
            {
                obj = this.createFunc(this);
            }
            if (obj is IPoolable)
            {
                IPoolable poolable = (IPoolable)obj;
                poolable.PrepareForUse();
            }
            return(obj);
        }
Exemplo n.º 5
0
        public bool PushToPool(string entityName, IPoolable poolableObject)
        {
            if (poolableObject == null)
            {
                Debug.LogError("Can't push object to pool! Object is null!");

                return(false);
            }

            if (string.IsNullOrEmpty(entityName))
            {
                Debug.LogError("Can't push object to pool! <Entity Name> is null or empty!", poolableObject as Object);

                return(false);
            }

            if (!m_Pool.ContainsKey(entityName))
            {
                m_Pool.Add(entityName, new List <IPoolable>());
            }

            if (m_Pool[entityName].Contains(poolableObject))
            {
                return(false);
            }

            m_Pool[entityName].Add(poolableObject);

            poolableObject.OnPoolPushEvent();

            return(true);
        }
Exemplo n.º 6
0
        public T PopFromPool <T>(string entityName)
        {
            if (string.IsNullOrEmpty(entityName))
            {
                return(default(T));
            }

            if (!m_Pool.ContainsKey(entityName))
            {
                return(default(T));
            }

            List <IPoolable> list = m_Pool[entityName];

            if (list.Count < 1)
            {
                return(default(T));
            }

            int       lastIndex      = list.Count - 1;
            IPoolable poolableObject = list[lastIndex];

            list.RemoveAt(lastIndex);

            poolableObject.OnPoolPopEvent();

            return((T)poolableObject);
        }
Exemplo n.º 7
0
 public static void TriggerPoolableReturn(IPoolable poolable)
 {
     if (OnPoolableReturn != null)
     {
         OnPoolableReturn(poolable);
     }
 }
Exemplo n.º 8
0
        /// <summary>
        /// Get an Available instance of the GameObjects Pool.
        /// </summary>
        /// <returns>The IPoolable reference associated with the GameObject instance.</returns>
        public IPoolable GetAvailable()
        {
            int i = index;

            do
            {
                if (!objectList[i].Alive)
                {
                    index = (i + 1) % objectList.Count;
                    return(objectList[i]);
                }
                i = (i + 1) % objectList.Count;
            } while (i != index);

            GameObject obj = Instantiate(prefab);

            obj.SetActive(false);
            IPoolable poolObj = obj.GetComponent <IPoolable>();

            if (limit == -1 || objectList.Count < limit)
            {
                obj.name = "Pool " + obj.name + " " + objectList.Count;

                objectList.Add(poolObj);
                poolObj.InPool = true;
            }
            return(poolObj);
        }
Exemplo n.º 9
0
        public IPoolable GetObject(string poolID)
        {
            if (string.IsNullOrEmpty(poolID))
            {
                return(null);
            }
            if (!objectsDict.ContainsKey(poolID))
            {
                return(null);
            }

            if (objectsDict[poolID].Count == 0)
            {
                foreach (var o in objects)
                {
                    if (o.GetComponent <IPoolable>().PoolID == poolID)
                    {
                        GameObject go = Instantiate(o);
                        go.SetActive(false);
                        objectsDict[poolID].Enqueue(go.GetComponent <IPoolable>());
                        break;
                    }
                }
            }

            IPoolable p = objectsDict[poolID].Dequeue();

            objectsDict[poolID].Enqueue(p);

            return(p);
        }
Exemplo n.º 10
0
            /// <summary>
            /// Releases a Component to a pool once came from pool
            /// </summary>
            /// <param name="c">a Component came from pool</param>
            public void Release(Component c)
            {
                if (!inPool.ContainsKey(c))
                {
                    Debug.LogError("This object is not a member of this pool, rejecting");
                    return;
                }

                if (inPool[c])
                {
                    Debug.LogError("This object is already releaseed to pool, rejecting");
                    return;
                }

                c.gameObject.SetActive(false);
                c.transform.SetParent(PoolRoot);

                inPool[c] = true;
                passives.Push(c);

                IPoolable p = c as IPoolable;

                if (p != null)
                {
                    p.OnPoolRelease();
                }
            }
Exemplo n.º 11
0
        protected T CreateItem(ref IPoolable poolable)
        {
            T item = CustomCreateItem(ref poolable);

            TotalCreatedItemsCount++;
            return(item);
        }
Exemplo n.º 12
0
    public GameObject SpawnFromPool(string tag, Vector3 position, Quaternion rotation)
    {
        if (!poolDictionary.ContainsKey(tag))
        {
            Debug.LogWarning("Pool with tag " + tag + " doesn't exist");
            return(null);
        }

        GameObject objToSpawn = poolDictionary[tag].Dequeue();

        objToSpawn.SetActive(true);
        objToSpawn.transform.position = position;
        objToSpawn.transform.rotation = rotation;

        IPoolable pooledObject = objToSpawn.GetComponent <IPoolable>();

        if (pooledObject != null)
        {
            pooledObject.OnObjectSpawn();
        }

        poolDictionary[tag].Enqueue(objToSpawn);

        return(objToSpawn);
    }
Exemplo n.º 13
0
        public IPoolable GetPoolableObject(Transform parentTrans)
        {
            IPoolable poolable = GetPoolableObject();

            poolable.transform.SetParent(parentTrans, false);
            return(poolable);
        }
Exemplo n.º 14
0
        public void Activate()
        {
            if (!activated)
            {
                ISerializator[] serializators = GetComponents <MonoBehaviour>().OfType <ISerializator>().ToArray();



                foreach (ISerializator serializedGameObject in serializators)
                {
                    IPoolable poolable = serializedGameObject.DeserializeForRuntime();



                    if (poolable != null)
                    {
                        if (instantiatedPoolables == null)
                        {
                            instantiatedPoolables = new List <IPoolable>();
                        }
                        instantiatedPoolables.Add(poolable);
                        poolable.Init();
                    }
                    else
                    {
                        Debug.Log("TrackChunk.ActivateTrackCHunk(): null poolable in serializator " + serializedGameObject.GetType());
                    }
                }
            }
            activated = true;
        }
Exemplo n.º 15
0
		public void Remove(IPoolable obj)
		{
			lock (this)
			{
				this.m_data.Remove(obj);
			}
		}
Exemplo n.º 16
0
    public Bullet CreateBullet(BulletTypes type, Vector2 pos)
    {
        Vector2 randV2 = UnityEngine.Random.insideUnitCircle.normalized * 5;

        GameObject toRetObj = null;
        IPoolable  poolable = ObjectPool.Instance.RetrieveFromPool(type);

        if (poolable != null)
        {
            toRetObj = poolable.GetGameObject;
        }
        else
        {
            toRetObj = _CreateBullet(type).gameObject;
        }
        Bullet toRet = toRetObj.GetComponent <Bullet>();

        if (!toRet)
        {
            Debug.LogError("Something went wrong in bullet factory, object: " + toRetObj.name + " did not contain a bullet script. Returning Null");
        }
        else
        {
            toRet.transform.position = pos;

            BulletManager.Instance.Addbullet(toRet);
        }



        return(toRet);
    }
Exemplo n.º 17
0
        private void Return(IPoolable poolable)
        {
            var poolable1 = (T)poolable;

            _freeItems.AddToBack(poolable1);
            _usedItems.Remove(poolable1);
        }
    /// <summary>
    /// "Aquires" object from its respective pool.
    /// Creates a new `Pool` and takes `poolable.GameObject` as its original instance in case the `Pool` is null.
    /// Pools using original instance id.
    /// Recommended to pass `poolable` that already has a pool unless you want to create a new one and use this one as original instance.
    /// </summary>
    /// <param name="poolable">Original instance or poolable with pool.</param>
    /// <returns>GameObject instance of aquired poolable.</returns>
    public GameObject Aquire(IPoolable poolable)
    {
#if UNITY_EDITOR
        if (poolable == null)
        {
            Debug.LogError(message: "`poolable` is null which could mean: 1. Object is null. 2. Object doesn't have a component that inherits IPoolable.");
        }

        if (poolable.Pool == null)
        {
            if (this._editorOnlyAddPoolsAutomatically)
            {
                new Pool(
                    originalInstance: poolable.GameObject,
                    initialCapacity: this._defaultInitialPoolCapacity,
                    dontDestroyOnLoad: false
                    );
            }
            else
            {
                //const char backspace = '\b';

                Debug.LogError(
                    message: $@"IPoolable - {poolable.GameObject} InstanceId: {poolable.GameObject.GetInstanceID()} doesn't have a Pool instance. Make sure you added pool and it has instances related to this poolable."
                    );
            }
        }
#endif

        return(poolable.Pool.Aquire().GameObject);
    }
Exemplo n.º 19
0
        PoolableInfo CreatePoolableInfo(IPoolable poolable, List <ModestTree.Util.ValuePair <Type, int> > priorities)
        {
            var match    = priorities.Where(x => poolable.GetType().DerivesFromOrEqual(x.First)).Select(x => (int?)(x.Second)).SingleOrDefault();
            int priority = match.HasValue ? match.Value : 0;

            return(new PoolableInfo(poolable, priority));
        }
Exemplo n.º 20
0
    //Main function used by everyone and by the functions above
    /// <summary>
    /// Creates a monster of given name at the location
    /// </summary>
    public Monster CreateMonster(string monsterName, Vector2 loc, Ingredient monsterIngredient)
    {
        GameObject toRetObj = null;
        IPoolable  poolable = ObjectPool.Instance.RetrieveFromPool(monsterName); //atm pool is not functional, will always return null

        if (poolable != null)
        {
            toRetObj = poolable.GetGameObject;
        }
        else
        {
            toRetObj = _CreateMonster(monsterName).gameObject;
        }
        Monster toRet = toRetObj.GetComponent <Monster>();

        if (!toRet)
        {
            Debug.LogError("Something went wrong in monster factory, object: " + toRetObj.name + " did not contain a monster script. Returning Null");
        }
        else
        {
            toRet.transform.position = loc;
            MonsterManager.Instance.AddMonster(toRet);
        }
        toRet.InitializeMonsterColor(monsterIngredient);
        return(toRet);
    }
Exemplo n.º 21
0
        private void Return(IPoolable item)
        {
            Debug.Assert(item != null);
            T poolable1    = (T)item;
            T previousNode = (T)item.PreviousNode;
            T nextNode     = (T)item.NextNode;

            if (previousNode != null)
            {
                previousNode.NextNode = nextNode;
            }

            if (nextNode != null)
            {
                nextNode.PreviousNode = previousNode;
            }

            if (item == _headNode)
            {
                _headNode = nextNode;
            }

            if (item == _tailNode)
            {
                _tailNode = previousNode;
            }

            if (_tailNode != null)
            {
                _tailNode.NextNode = null;
            }
            _freeItems.AddToBack(poolable1);
            ItemReturned?.Invoke((T)item);
        }
Exemplo n.º 22
0
 public void Remove(IPoolable obj)
 {
     lock (this)
     {
         this.m_data.Remove(obj);
     }
 }
Exemplo n.º 23
0
    /// <summary>
    /// It is used for getting objects from pool
    /// </summary>
    /// <typeparam name="T">Type of object</typeparam>
    /// <returns>Returns the requested object</returns>
    public T Get <T>()
    {
        //Searchs if ialready has the object
        for (int i = 0; i < poolable.Count; i++)
        {
            if (poolable[i] is T)
            {
                IPoolable go = poolable[i];
                go.GetGameObject.SetActive(true);
                poolable.Remove(go);
                if (onObjectCreate != null)
                {
                    onObjectCreate(go.GetGameObject);
                }
                return((T)go);
            }
        }

        //Search the object in prefabricated objects
        for (int i = 0; i < prefs.Length; i++)
        {
            //Returns object
            if (prefs[i].GetComponent <T>() != null)
            {
                GameObject instance = Instantiate(prefs[i]);
                if (onObjectCreate != null)
                {
                    onObjectCreate(instance);
                }
                return(instance.GetComponent <T>());
            }
        }
        //If it has not the object, throws exception
        throw new System.Exception("There is no " + typeof(T));
    }
Exemplo n.º 24
0
            /// <summary>
            /// Grows Cache by one
            /// </summary>
            /// <returns>success</returns>
            public bool Instantiate()
            {
                if ((belongings.Count) >= maxSize)
                {
                    Debug.LogError("Pool Reached max size of " + maxSize + " wont create new one.");
                    return(false);
                }

                GameObject go = GameObject.Instantiate(prefab);
                Component  c  = go.GetComponent(componentType);

                go.SetActive(false);
                go.name = prefab.name;
                go.transform.SetParent(PoolRoot);

                belongings.Add(c);
                inPool.Add(c, true);
                passives.Push(c);

                IPoolable p = c as IPoolable;

                if (p != null)
                {
                    p.OnPoolInstantiate();
                }

                return(true);
            }
Exemplo n.º 25
0
            /// <summary>
            /// Gets a Component from pool
            /// </summary>
            /// <returns>a component removed from pool</returns>
            public Component Get()
            {
                if (passives.Count <= 0)
                {
                    if (!Instantiate())
                    {
                        return(null);
                    }
                }

                Component c = passives.Pop();

                inPool[c] = false;

                c.gameObject.transform.SetParent(null);
                c.gameObject.SetActive(true);

                IPoolable p = c as IPoolable;

                if (p != null)
                {
                    p.OnPoolGet();
                }

                return(c);
            }
Exemplo n.º 26
0
        public IPoolable Get(Type type, Transform parent = null, bool noOnGet = false)
        {
            IPoolable item = null;

            if (_Pool.Pool.TryGetValue(type, out Queue <IPoolable> pool))
            {
                if (pool.Count < _Pool.StartSize[type] / 4 && !_Pool.IsBuilding[type])
                {
                    Container.StartCoroutine(Build(type));
                }

                if (pool.Count == 0)
                {
                    item = ManualBuild(type);
                }
                else
                {
                    item = pool.Dequeue();
                }

                if (!noOnGet)
                {
                    item.OnGet(parent);
                }
            }
            return(item);
        }
    // pos, dir, velo to create bullet


    public Bullet CreateBullet(string bulletName, Transform position, Vector2 direction)
    {
        GameObject toRetObj = null;
        IPoolable  poolable = ObjectPool.Instance.RetrieveFromPool(bulletName);

        if (poolable != null)
        {
            toRetObj = poolable.GetGameObject;
        }
        else
        {
            toRetObj = _CreateBullet(bulletName, position, direction).gameObject;
        }
        Bullet toRet = toRetObj.GetComponent <Bullet>();

        if (!toRet)
        {
            Debug.LogError(toRetObj.name + " did not contain a Bullet script. Returning Null");
        }
        else
        {
            BulletManager.Instance.AddBullet(toRet);
        }
        return(toRet);
    }
Exemplo n.º 28
0
        public T GetObject <T>() where T : class, IPoolable, new()
        {
            int checkedIndices = 0;
            int i = lastAvailable;

            while (checkedIndices < pooledObjects.Count)
            {
                IPoolable a = pooledObjects[i];

                if (a.IsAvailable())
                {
                    lastAvailable = i;
                    a.Retrieve();
                    return(a as T);
                }

                i++;
                checkedIndices++;

                if (i >= pooledObjects.Count)
                {
                    i = 0;
                }
            }

            T result = new T();

            result.Retrieve();

            pooledObjects.Add(result);

            return(result);
        }
Exemplo n.º 29
0
        public T Take()
        {
            T         obj;
            IPoolable pooled = null;

            if (Pool.Count < 1)
            {
                switch (Behaviour)
                {
                case PoolBehavior.Grow:
                    obj    = CreateNewInstance();
                    pooled = obj as IPoolable;
                    pooled?.PoolInitialize();
                    break;

                case PoolBehavior.Fixed:
                    return(default);

                default:
                    throw new ArgumentOutOfRangeException();
                }
            }
            else
            {
                obj = Pool.Take(Pool.Count - 1);
            }

            Active.Add(obj);
            pooled?.TakenFromPool();
            return(obj);
        }
Exemplo n.º 30
0
        public override IPoolable DeserializeForEditor()
        {
            IPoolable poolable = base.DeserializeForEditor();

            poolable.GetGameObject.transform.localScale = scale;
            return(poolable);
        }
Exemplo n.º 31
0
        public void ReturnInstance(IPoolable instance)
        {
            Type type = instance.GetType();
            ObjectPool <IPoolable> pool = GetOrCreatePool(type);

            pool.ReturnInstance(instance);
        }
Exemplo n.º 32
0
		public void Set(IPoolable obj)
		{
			lock (this)
			{
				this.m_setCount++;
				this.m_data.Add(obj);
			}
		}
Exemplo n.º 33
0
		public void Set(IPoolable obj, string name = null)
		{
			if (string.IsNullOrEmpty(name)) name = "System";
			lock (this)
			{
				if (!this.m_data.ContainsKey(name))
				{
					var obj0 = this.m_manager == null ? new ObjectSet() : this.m_manager.Apply("Self.ObjectSet", "admin") as ObjectSet;
					this.m_data.Add(name, obj0);
				}
				this.m_data[name].Set(obj);
			}
		}
Exemplo n.º 34
0
		public void Remove(IPoolable obj, string name = null)
		{
			if (string.IsNullOrEmpty(name)) name = "System";
			lock (this)
			{
				if (this.m_data.ContainsKey(name))
				{
					this.m_data[name].Remove(obj);
					if (this.m_data[name].Count == 0)
					{
						var obj0 = this.m_data[name];
						this.m_data.Remove(name);
						if (this.m_manager != null && obj0 is IPoolable)
						{
							this.m_manager.Recycle(obj0 as IPoolable);
						}
					}
				}
			}
		}
Exemplo n.º 35
0
		public void Recycle(IPoolable obj)
		{
			string usage = obj.Usage;
			this.m_busyPool.Remove(obj, usage);
			this.m_idlePool.Set(obj, obj.ClassName);
		}
Exemplo n.º 36
0
 private void ObjectDisposing(IPoolable pooledObject, bool alive)
 {
     try {
         lock(this.Busy) {
             this.Busy.Remove(pooledObject);
         }
         if(alive) {
             lock(this.Free) {
                 if(!this.Free.Contains(pooledObject)) {
                     this.Free.Push(pooledObject);
                 }
             }
         } else {
             pooledObject.Dispose();
         }
     } catch(Exception e) {
         ExceptionService.Publish(e);
     }
 }