i try to make object pooling watching the tutorial from this channel brackey
The object pooling itself works but when the object spawn it gets out of hand
Here’s the video
Here are my Pooling Object scripts which I attached this into my Object Square
using System.Collections;
public class ObstacleObject : MonoBehaviour, IPooledObject
{
[HideInInspector]
public int xRange = 3;
private int currentPos = 1;
private List<Vector2> circlePos = new List<Vector2>()
{
new Vector2(-4.3f, 8f),
new Vector2(0.5f, 8f),
new Vector2(4.3f, 8f)
};
void Update()
{
currentPos++;
if (currentPos > 2)
{
currentPos = 0;
}
}
public void OnObjectSpawn()
{
int xPosisition = Random.Range(0 - xRange, xRange + 0);
transform.position = new Vector2(xPosisition, 6f);
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.CompareTag("whut"))
{
transform.position = circlePos[currentPos];
}
}
}
Here are my Pooling Object scripts which I attached into my gamemanager
class PoolingObject : MonoBehaviour
{
public List<Pool> pools;
public Dictionary<string, Queue<GameObject>> poolDictionary;
#region singleton
public static PoolingObject Instance;
void Awake()
{
Instance = this;
}
#endregion
void Start()
{
poolDictionary = new Dictionary<string, Queue<GameObject>>();
foreach (Pool pool in pools)
{
Queue<GameObject> objectPool = new Queue<GameObject>();
for (int i = 0; i < pool.size; i++)
{
GameObject obj = Instantiate(pool.prefab);
obj.SetActive(false);
objectPool.Enqueue(obj);
}
poolDictionary.Add(pool.objectTag, objectPool);
}
}
public GameObject SpawnPool(string objectTag, Vector2 posisition)
{
GameObject objectSpawn = poolDictionary[objectTag].Dequeue();
objectSpawn.SetActive(true);
objectSpawn.transform.position = posisition;
IPooledObject pooledObj = objectSpawn.GetComponent<IPooledObject>();
if (pooledObj != null)
{
pooledObj.OnObjectSpawn();
}
poolDictionary[objectTag].Enqueue(objectSpawn);
return objectSpawn;
}
}
Here are my Pooling Object scripts which I attached this to my spawner object
class Spawner : MonoBehaviour
{
PoolingObject objectPooling;
void Start()
{
objectPooling = PoolingObject.Instance;
}
void FixedUpdate()
{
objectPooling.SpawnPool("Square", transform.position);
}
}