Skip to content

Commit

Permalink
optimizing the code and implementing singleton
Browse files Browse the repository at this point in the history
  • Loading branch information
ertanturan committed Sep 21, 2020
1 parent 2df7042 commit 501b7e2
Show file tree
Hide file tree
Showing 4 changed files with 46 additions and 10 deletions.
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
using System.Collections.Generic;
using UnityEngine;

public class ObjectPooler : MonoBehaviour
public class ObjectPooler : SceneSingleton<ObjectPooler>
{

public Dictionary<PooledObjectType, Queue<GameObject>> PoolDictionary;
Expand All @@ -10,13 +10,6 @@ public class ObjectPooler : MonoBehaviour
private Dictionary<PooledObjectType, int> _poolIndexes = new Dictionary<PooledObjectType, int>();
private Dictionary<PooledObjectType, Transform> _poolMasters = new Dictionary<PooledObjectType, Transform>();

public static ObjectPooler Instance;

private void Awake()
{
Instance = this;
}

private void Start()
{
PoolDictionary = new Dictionary<PooledObjectType, Queue<GameObject>>();
Expand Down Expand Up @@ -98,17 +91,21 @@ public void Despawn(GameObject obj)
{
PooledObjectType tag = obj.GetComponent<IPooledObject>().PoolType;

if (tag != null)
if (tag != null && PoolDictionary.ContainsKey(tag))
{


PoolDictionary[tag].Enqueue(obj);

IPooledObject iPooledObj = obj.GetComponent<IPooledObject>();
if (iPooledObj != null) iPooledObj.OnObjectDespawn();
obj.SetActive(false);


}
else
{
Debug.LogWarning("Trying to despawn object which is not pooled !");
Debug.LogError("Trying to despawn object which is not pooled !");
}

}
Expand Down
8 changes: 8 additions & 0 deletions Assets/CustomTools/Sıngleton.meta

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

20 changes: 20 additions & 0 deletions Assets/CustomTools/Sıngleton/SceneSingleton.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
using UnityEngine;

public class SceneSingleton<T> : MonoBehaviour
where T : Component
{
static T s_instance = null;

public static T Instance
{
get
{
if (s_instance == null)
{
s_instance = Object.FindObjectOfType<T>();
}

return s_instance;
}
}
}
11 changes: 11 additions & 0 deletions Assets/CustomTools/Sıngleton/SceneSingleton.cs.meta

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 501b7e2

Please sign in to comment.