Example #1
0
    //Add an object to the pool
    public void AddToPool(PoolID id, GameObject poolObject)
    {
        //If id exists in dictionary enqueue object to queue
        if (pooledObjects.ContainsKey(id))
        {
            //Prevents from adding if already in queue
            if (!pooledObjects[id].Contains(poolObject))
            {
                pooledObjects[id].Enqueue(poolObject);
            }
        }

        //Create new dictionary entry with object as it's first element
        else
        {
            pooledObjects.Add(id, new Queue <GameObject>(new[] { poolObject }));
        }

        //Check if there exits a parent for this object
        if (!poolParents.ContainsKey(id))
        {
            CreatePoolParent(id);
        }

        //Deactivate the object set it as a child and center it's position
        poolObject.SetActive(false);
        poolObject.transform.SetParent(poolParents[id]);
        poolObject.transform.localPosition = Vector3.zero;
    }
Example #2
0
    public GameObject GetPooledObject(PoolID id)
    {
        //Check if dictionary contains id
        if (pooledObjects.ContainsKey(id))
        {
            //Get the first element in the queue and reset it's parent
            GameObject poolItem = pooledObjects[id].Dequeue();
            poolItem.transform.SetParent(null);
            poolItem.SetActive(true);

            //If queue is empty remove it from the dictionary
            if (pooledObjects[id].Count <= 0)
            {
                pooledObjects.Remove(id);
            }

            Debug.Log($"Getting {poolItem.name} from pool");
            return(poolItem);
        }

        //Get an instantiated element from the factory
        else
        {
            GameObject factoryObject = FactoryManager.Instance.GetItem(id);
            Debug.Log($"Created {factoryObject.name} from Factory");
            return(factoryObject);
        }
    }
Example #3
0
    //Create an empty parent to hold the pooled item of the same type
    void CreatePoolParent(PoolID id)
    {
        GameObject poolParent = new GameObject($"{id}");

        poolParent.transform.SetParent(transform);
        poolParents.Add(id, poolParent.transform);
    }
Example #4
0
        public PoolableObject UnpoolObject(PoolID theID)
        {
            PoolData thePool = GetPoolByID(theID);

            PoolableObject theObject = null;

            //	Pool has nothing available, create new default object
            //	TODO: Check if pool is getting too small during update and create several at once
            if (thePool.pooledObjects.Count == 0)
            {
                theObject = InstantiateDefaultObject(thePool);
            }
            else
            {
                theObject = thePool.pooledObjects[0];
                thePool.pooledObjects.RemoveAt(0);
            }

            //	Add to Unpooled list
            thePool.unpooledObjects.Add(theObject);
            //	Call the object's specific Unpooling functionality
            theObject.Unpool();

            return(theObject);
        }
Example #5
0
    private IEnumerator Destroy_Object(PoolID obj_pid, float time = 0.0f)
    {
        yield return(new WaitForSeconds(time));

        Pooled_Object po = (Pooled_Object)_objects[obj_pid.id];

        po.ReturnObject(obj_pid.gameObject);
    }
        /*public bool startPooled = true;
         * public PoolID theCategory = PoolID.None;*/

        #endregion


        #region Private Variables

        /*private PoolManager _poolManager;
         * private bool _isPooled;*/

        #endregion


                #if UNITY_EDITOR
        public override void DrawInspector()
        {
            base.DrawInspector();

            /*startPooled = EditorGUILayout.Toggle ("Start Pooled", startPooled);
             * theCategory = (PoolID)EditorGUILayout.EnumPopup ("Pool Category", theCategory);*/

            theID = (PoolID)EditorGUILayout.EnumPopup("Pool ID", theID);
        }
Example #7
0
    /// <summary>
    /// Destroy the specified object by removing the reference of the passed object, disabling the major component
    /// </summary>
    /// <param name="obj">Object.</param>
    public void PS_Destroy(GameObject obj, float time = 0.0f)
    {
        PoolID obj_pid = obj.GetComponent <PoolID>();

        // Object is in our pool
        if (obj_pid != null)
        {
            StartCoroutine(Destroy_Object(obj_pid, time));
        }
        else
        {
            Debug.LogWarning(string.Format("{0} does not belong in the pool system since it was not Instantiated by the pooling system"));
        }
    }
Example #8
0
        private PoolData GetPoolByID(PoolID theID)
        {
            for (int i = 0; i < poolDatas.Count; i++)
            {
                if (theID == poolDatas[i].theID)
                {
                    return(poolDatas[i]);
                }
            }

                        #if UNITY_EDITOR
            Debug.LogError("PoolManager attempted to GetPoolByID using an ID that is not in the poolDatas: " + theID.ToString());
                        #endif
            return(null);
        }
Example #9
0
    public GameObject GetItem(PoolID id)
    {
        //Return an instantiated object from the catalog
        if (Catalog.ContainsKey(id))
        {
            FactoryCategory category = Catalog[id];            //Get the current category
            GameObject      item     = category.GetRandomIten; //Get a random item

            return(Instantiate(item));                         //Return an instance of this object
        }
        else
        {
            Debug.LogError($"Missing key {id} from factory");
            return(null);
        }
    }
Example #10
0
    /// <summary>
    /// Pretend to instantiate the specified object, put it in a pool. If the object is not in the existing cache pool
    /// put it in and reuse. If the object already exist, reuse the exisiting pool objects. If there is no more objects
    /// in the pool, expanded the pool to add more.
    /// </summary>
    /// <param name="obj">Object.</param>
    public GameObject PS_Instantiate(GameObject obj)
    {
        GameObject o       = null;
        PoolID     obj_pid = obj.GetComponent <PoolID>();

        if (obj_pid != null && _objects.Count == 0)
        {
            Debug.LogError("PoolID is already contained on the prefabs. Make sure to remove them before start.");
            return(null);
        }

        // Cahced already, search for the correct pool
        if (obj_pid != null)
        {
            Pooled_Object po = (Pooled_Object)_objects[obj_pid.id];
            if (po.main_obj.GetComponent <PoolID>().id == obj_pid.id)
            {
                o = po.GetObject();
            }
        }
        // No cache of the object
        else
        {
            // Create new object and have it generate a pool id
            Pooled_Object po = new Pooled_Object(obj);

            // Get pool id for this object now
            obj_pid = obj.GetComponent <PoolID>();

            // Add object into our table of pooled objects
            _objects.Add(obj_pid.id, po);

            // Get the object of the current pooled object
            o = po.GetObject();

            if (object_hierarchy)
            {
                // Root the pooled objects into a true root object for the entire pooling system
                po.pool_root.transform.parent = _root.transform;
            }
        }

        return(o);
    }
Example #11
0
 // Get a pooled object by ID (faster)
 public static GameObject GetPooledObject(PoolID id, bool autoActivate = true)
 {
     return(GetPooledObject(id, Vector3.zero, autoActivate));
 }
        protected void tvSkills_TreeNodeCheckChanged(object sender, TreeNodeEventArgs e)
        {
            if (e.Node.Checked)
            {
                TreeView OrigTreeView = new TreeView();
                CopyTreeNodes(tvSkills, OrigTreeView);

                MarkParentNodes(e.Node);

                List <cSkillPool> oSkillList = Session["CharacterSkillPools"] as List <cSkillPool>;

                DataTable dtPointsSpent = new DataTable();
                dtPointsSpent.Columns.Add(new DataColumn("PoolID", typeof(int)));
                dtPointsSpent.Columns.Add(new DataColumn("CPSpent", typeof(double)));
                dtPointsSpent.Columns.Add(new DataColumn("TotalCP", typeof(double)));

                foreach (cSkillPool cSkill in oSkillList)
                {
                    DataRow dNewRow = dtPointsSpent.NewRow();
                    dNewRow["PoolID"]  = cSkill.PoolID;
                    dNewRow["TotalCP"] = cSkill.TotalPoints;
                    dNewRow["CPSpent"] = 0.0;

                    dtPointsSpent.Rows.Add(dNewRow);
                }

                DataTable dtAllSkills = Session["SkillNodes"] as DataTable;
                double    TotalSpent  = 0.0;

                DataTable dtSkillCosts = new DataTable();
                dtSkillCosts.Columns.Add(new DataColumn("Skill", typeof(string)));
                dtSkillCosts.Columns.Add(new DataColumn("Cost", typeof(double)));
                dtSkillCosts.Columns.Add(new DataColumn("SortOrder", typeof(int)));
                dtSkillCosts.Columns.Add(new DataColumn("SkillID", typeof(int)));

                double TotalCP = 0.0;
                double.TryParse(Session["TotalCP"].ToString(), out TotalCP);

                string sSkills = "";
                foreach (TreeNode SkillNode in tvSkills.CheckedNodes)
                {
                    int iSkillID;
                    if (int.TryParse(SkillNode.Value, out iSkillID))
                    {
                        DataRow[] dSkillRow = dtAllSkills.Select("CampaignSkillNodeID = " + iSkillID.ToString());
                        if (dSkillRow.Length > 0)
                        {
                            double SkillCost;
                            int    PoolID;
                            if ((double.TryParse(dSkillRow[0]["SkillCPCost"].ToString(), out SkillCost)) &&
                                (int.TryParse(dSkillRow[0]["CampaignSkillPoolID"].ToString(), out PoolID)))
                            {
                                if (dtSkillCosts.Select("SkillID = " + iSkillID.ToString()).Length == 0)
                                {
                                    DataRow[] dSkillCountRow = dtPointsSpent.Select("PoolID = " + PoolID.ToString());
                                    if (dSkillCountRow.Length > 0)
                                    {
                                        dSkillCountRow[0]["CPSpent"] = (double)(dSkillCountRow[0]["CPSpent"]) + SkillCost;
                                    }
                                }
                                TotalSpent += SkillCost;
                                if (SkillCost > 0)
                                {
                                    sSkills += dSkillRow[0]["SkillName"].ToString() + ":" + SkillCost.ToString() + ", ";
                                }
                                DataRow dNewRow = dtSkillCosts.NewRow();
                                dNewRow["Skill"]     = dSkillRow[0]["SkillName"].ToString();
                                dNewRow["Cost"]      = SkillCost;
                                dNewRow["SkillID"]   = iSkillID;
                                dNewRow["SortOrder"] = 10;
                                dtSkillCosts.Rows.Add(dNewRow);
                            }
                        }
                    }
                }

                bool bSpentTooMuch = false;

                foreach (DataRow dCostRow in dtPointsSpent.Rows)
                {
                    double CPSpent;
                    double TotalCPForPool;
                    if ((double.TryParse(dCostRow["TotalCP"].ToString(), out TotalCPForPool)) &&
                        (double.TryParse(dCostRow["CPSpent"].ToString(), out CPSpent)))
                    {
                        if (CPSpent > TotalCPForPool)
                        {
                            bSpentTooMuch = true;
                        }
                    }
                }

                if (bSpentTooMuch)
                {
                    tvSkills.Nodes.Clear();
                    TreeView OrigTree = Session["CurrentSkillTree"] as TreeView;
                    CopyTreeNodes(OrigTree, tvSkills);

                    AlertMessage = "You do not have enough CP to buy that.";
                }
                else
                {
                    bMeetAllRequirements = true;
                    CheckForRequirements(e.Node.Value);
                    if (!bMeetAllRequirements)
                    {
                        tvSkills.Nodes.Clear();
                        TreeView OrigTree = Session["CurrentSkillTree"] as TreeView;
                        CopyTreeNodes(OrigTree, tvSkills);
                        e.Node.Checked = false;
                        AlertMessage   = "You do not have all the requirements to purchase that item.";
                    }
                    else
                    {
                        CheckAllNodesWithValue(e.Node.Value, true);
                    }
                }
                List <TreeNode> FoundNodes = FindNodesByValue(e.Node.Value);
                foreach (TreeNode t in FoundNodes)
                {
                    t.ShowCheckBox = false;
                    EnableChildren(t);
                }
            }
            else
            {
                // Check to see if we should not allow them to sell it back.
                if (ViewState["SkillList"] != null)
                {
                    int iSkillID;
                    if (int.TryParse(e.Node.Value, out iSkillID))
                    {
                        List <int> SkillList = ViewState["SkillList"] as List <int>;
                        if (SkillList.Contains(iSkillID))
                        {
                            if (hidAllowCharacterRebuild.Value == "0")
                            {
                                e.Node.Checked = true;
                                AlertMessage   = "This campaign is not allowing skills to be rebuilt at this time.  Once a skill is selected and saved, it cannot be changed.";
                                //ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(),
                                //        "MyApplication",
                                //        jsString,
                                //        true);
                                return;
                            }
                        }
                    }
                }
                DeselectChildNodes(e.Node);
                CheckAllNodesWithValue(e.Node.Value, false);

                List <TreeNode> FoundNodes = FindNodesByValue(e.Node.Value);
                foreach (TreeNode t in FoundNodes)
                {
                    t.Text         = t.Text.Replace("grey", "black");
                    t.ImageUrl     = "";
                    t.ShowCheckBox = true;
                    EnableChildren(t);
                }
            }
            CheckExclusions();
            ListSkills();
            Session["CurrentSkillTree"] = tvSkills;

            lblMessage.Text      = "Skills Changed";
            lblMessage.ForeColor = Color.Red;
        }
Example #13
0
 // Get how many objects are currently active in a pool
 public int GetActiveObjectCount(PoolID id)
 {
     return(m_Categories[id.catID].m_Pools[id.typeID].GetActiveObjectCount());
 }
Example #14
0
    // Member function
    private GameObject GetPooledObjectM(PoolID id, Vector3 position, bool autoActivate = true)
    {
        if (id.catID == -1 || id.typeID == -1)
        {
            return(null);
        }

        // Note that this will most likely crash if you tamper with the ID
        var pool = m_Categories[id.catID].m_Pools[id.typeID];

        // Search for available pooled objects
        foreach (var po in pool.pooledObjects)
        {
            if (!po.go.activeInHierarchy)
            {
                // Available object found
                po.go.transform.SetParent(null);
                po.go.transform.position = position;
                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)
        {
            Stopwatch sw = null;
            if (logging)
            {
                sw = new Stopwatch();
                sw.Start();
            }
            PooledObject po = new PooledObject();
            po.go = Instantiate(pool.pooledObject);
            pool.pooledObjects.Add(po);
            po.go.transform.SetParent(null);
            po.go.transform.position = position;
            if (po.go && autoActivate)
            {
                po.go.SetActive(true);
            }
            po.setSpawnTime(Time.time);
            if (logging)
            {
                sw.Stop();
                Log("Expanding pool of [" + m_Categories[id.catID].name + ", " + pool.name + "] due to insufficient inactive objects (" + sw.ElapsedMilliseconds + " ms).");
            }
            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;
                }
            }

            po.go.SetActive(false);
            po.go.transform.SetParent(null);
            po.go.transform.position = position;
            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);
    }
Example #15
0
    public static GameObject GetPooledObject(string category, string type, Vector3 position, bool autoActivate = true)
    {
        PoolID id = GetPoolID(category, type);

        return(manager.GetPooledObjectM(id, position, autoActivate));
    }
Example #16
0
 public static GameObject GetPooledObject(PoolID id, Vector3 position, bool autoActivate = true)
 {
     return(manager.GetPooledObjectM(id, position, autoActivate));
 }
Example #17
0
 public static string GetTypeName(PoolID id)
 {
     return(manager.m_Categories[id.catID].m_Pools[id.typeID].name);
 }
Example #18
0
 public static string GetCategoryName(PoolID id)
 {
     return(manager.m_Categories[id.catID].name);
 }
Example #19
0
        public override void DrawInspector()
        {
            base.DrawInspector();

            theID = (PoolID)EditorGUILayout.EnumPopup("Pool ID", theID);
        }