My ObjectPool isn't working and I have written all codes correctly

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

public class ObjectPool : MonoBehaviour

{

[SerializeField] GameObject enemyPrefab;

[SerializeField] int poolSize = 5;

[SerializeField] float spawnTimer = 1f;

GameObject[] pool;

void Awake()

{

    PopulatePool();

}

void Start()

{

    StartCoroutine(SpawnEnemy());

}

void PopulatePool()

{

    pool = new GameObject[poolSize];

    for(int i = 0; i < pool.Length; i++)

    {

        pool[i] = Instantiate(enemyPrefab, transform);

        pool[i].SetActive(false);

    }

}

void EnableObjectInPool()

{

    for(int i = 0; i < pool.Length; i++)

    {

        if(pool[i].activeInHierarchy == false)

        {

            pool[i].SetActive(true);

            return;

        }

    }

}

IEnumerator SpawnEnemy()

{

    while(true)

    {

        Instantiate(enemyPrefab, transform);

        EnableObjectInPool();

        yield return new WaitForSeconds(spawnTimer);

    }

}

}

So let me guess, it spawns 2 enemies every second for the first 5 seconds, and 1 enemy every second thereafter?

yes and I tried researching couldn’t find any solution

So what’s wrong? That’s what the code says it’s going to do.

I don’t understand

What’s wrong? What are you trying to accomplish? What’s not working the way you were expecting.

my enemies keeps spwaning multiple times instead of just 5 times just like in the lecture

I don’t know what the lecture this is about, but delete the “instantiate” line and if I understand you right, that should get you going right.

Thanks let me try it out I will give you a feedback if it works


Well it prints out this error!!

There might be a typo in your code, @abdullahi_odukoya. Double click on the error message. To which line in your code does it refer? Compare that line with Rick’s code.

I already did that still same error

As nina mentioned, which line in your code does the error refer to? It sounds like something more than the Instantiate deletion has changed in your code.

It’s line 23.

First, it looks like you deleted the wrong Instantiate and second, it looks like you only deleted the word Instantiate so now you have

void PopulatePool()
{
    pool = new GameObject[poolSize];
    for(int i = 0; i < pool.Length; i++)
    {
        pool[i] = (enemyPrefab, transform); // <- this is now a tuple and cannot be converted to GameObject
        pool[i].SetActive(false);
    }
}

I’m kinda guessing based on the error being on line 23 (I think) and the error message you get

Edit I looked at the code for this lecture. It’s like @MichaelP said: Your SpawnEnemy should not have the whole Instantiate line

IEnumerator SpawnEnemy()
{
    while(true)
    {
        EnableObjectInPool();
        yield return new WaitForSeconds(spawnTimer);
    }
}
1 Like

Privacy & Terms