I’m trying to optimise my Mobile Auto-runner Game by replacing Instantiating and Deleting with Object Pooling. However, I can’t seem to figure out how to fix my script issue, as asset creation is by far my primary skill, and I’m still a beginner when it comes to scripting. I’ve been told that I need to provide an INT as a key and I have no idea how to do that. My autorunner uses 4 tiles that loop.
using System.Collections;
using UnityEngine;
using System.Collections.Generic;
public class TileManager : MonoBehaviour
{
public GameObject[] tilePrefabs;
Dictionary<int, List<GameObject>> tilePool = new Dictionary<int, List<GameObject>>();
private Transform playerTransform;
private float spawnZ = -10f;
private float tileLength = 27.7016f;
private float safeZone = 22.5f;
private int amnTilesOnScreen = 4;
private int lastPrefabIndex = 0;
private List<GameObject> activeTiles;
// Start is called before the first frame update
private void Start()
{
activeTiles = new List<GameObject>();
playerTransform = GameObject.FindGameObjectWithTag("Player").transform;
for (int i = 0; i < amnTilesOnScreen; i++)
{
if (i < 2)
SpawnTile(0);
else
SpawnTile();
}
}
// Update is called once per frame
private void Update()
{
if (playerTransform.position.z - safeZone > (spawnZ - amnTilesOnScreen * tileLength))
{
SpawnTile();
DeleteTile();
}
}
private void SpawnTile(int prefabIndex = -1)
{
//make sure prefabIndex is set correctly.
if (!tilePool.ContainsKey(prefabIndex)) tilePool.Add(prefabIndex, new List<GameObject>());
GameObject go = tilePool[prefabIndex].Find(x => !x.activeSelf); // find disabled gameobject to reuse
if (go == null)
{
go = Instantiate(tilePrefabs[prefabIndex]) as GameObject;
tilePool[prefabIndex].Add(go);
}
//set position for go and else
}
private void DeleteTile()
{
activeTiles[0].SetActive(false);//disable for reuse
activeTiles.RemoveAt(0);
}
private int RandomPrefabIndex()
{
if (tilePrefabs.Length <= 1)
return 0;
int randomIndex = lastPrefabIndex;
while (randomIndex == lastPrefabIndex)
{
randomIndex = Random.Range(0, tilePrefabs.Length);
}
lastPrefabIndex = randomIndex;
return randomIndex;
}
}
Before you link me to this other thread ( Object Pooling ), I already read it and it did not provide me with the help I needed.
I would seriously appreciate help as I’ve been stuck on this issue for quite a while.