- Home /
Question by
SolidSlish · Nov 26, 2019 at 03:47 AM ·
instantiateobjectspawnconnectionpooling
How to Use Object Pooling for a 3D Autorunner? As Opposed to Instantiate?
So, for my project which is a Subway Surfers type game, I'm Instantiating when its clear I should be Pooling. My character moves along the Z Axis and I instantiate and then delete roughly 12 Obstacles every 5 seconds. My Draw Call is at a consistent 250 while my tris is at 144k.
How do I make a pooling system similar to my current system? Heres my current script. If possible, I want to make each tile seamlessly connect.
using System.Collections;
using UnityEngine;
using System.Collections.Generic;
public class TileManager : MonoBehaviour
{
public GameObject[] tilePrefabs;
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)
{
GameObject go;
if (prefabIndex == -1)
go = Instantiate(tilePrefabs[RandomPrefabIndex()]) as GameObject;
else
go = Instantiate(tilePrefabs[prefabIndex]) as GameObject;
go.transform.SetParent(transform);
go.transform.position = Vector3.forward * spawnZ;
spawnZ += tileLength;
activeTiles.Add (go);
}
private void DeleteTile()
{
Destroy(activeTiles[0]);
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;
}
}
Comment
Your answer
Follow this Question
Related Questions
Instantiate Prefab at random 1 Answer
Spawn many object 1 Answer
Spawning different random objects at the same position? 2 Answers
How to spawn different object from Prefabs folder 0 Answers
Give object velocity based on spawn object rotation? 2 Answers