- Home /
Question by
Bentley100 · Sep 11, 2021 at 10:11 PM ·
generationobject pool
2d object pooling platform generation for mobile not working
Hi, i am working on a mobile game where you jump up onto platform but instead of spawning 200 individual platforms i was informed of object pooling. i have followed this brackeys tutorial. The problem with the spawning is that they spawn but the are set to false and not in the right position. Here is the Object pooling script
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Pool;
public class ObjectPooling : MonoBehaviour
{
[Serializable]
public class pool {
public string tag;
public GameObject prefab;
public int size;
}
public List<pool> pools;
public Dictionary<string, Queue<GameObject>> poolDictonary;
public static ObjectPooling instance;
private void Awake()
{
instance = this;
}
private void Start()
{
poolDictonary = 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);
}
poolDictonary.Add(pool.tag, objectPool);
}
}
public GameObject SpawnFromPool(string tag, Vector3 position, Quaternion rotation)
{
if(!poolDictonary.ContainsKey(tag))
{
Debug.LogWarning("pool with tag" + tag +"dosnt exist.");
return null;
}
GameObject objectToSpawn = poolDictonary[tag].Dequeue();
objectToSpawn.SetActive(true);
objectToSpawn.transform.position = position;
objectToSpawn.transform.rotation = rotation;
poolDictonary[tag].Enqueue(objectToSpawn);
return objectToSpawn;
}
}
and here is the generation script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LevelGen : MonoBehaviour
{
ObjectPooling objectPooler;
public GameObject platformPrefab;
public GameObject platformPrefabmov;
public int numberOfPlatforms = 200;
public float LevelWidth = 3f;
public float minY = .2f;
public float maxY = 1.5f;
// Use this for initialization
void Start() {
objectPooler = ObjectPooling.instance;
Vector3 spawnPosition = new Vector3();
for (int i = 0; i < numberOfPlatforms; i++)
{
spawnPosition.y += Random.Range(minY, maxY);
spawnPosition.x = Random.Range(-LevelWidth, LevelWidth);
objectPooler.SpawnFromPool("cube", transform.position, Quaternion.identity);
}
}
// Update is called once per frame
void Update()
{
}
}
The old way it spawned was Instantiate(platformPrefab, spawnPosition, Quaternion.identity);
thanks
Comment
Your answer

Follow this Question
Related Questions
Object pulling prefabs that are randomly generating between random points? 0 Answers
Procedural Random Walk Dungeon Generator? 2 Answers
Block based map generator 5 Answers
Procedurally Generated Room System... 1 Answer
Random Room Generator 1 Answer