ObjectPooler not spawning object correctly all the time

I have made this ObjectPooler, but sometimes when i call the instanciateFromPool function to spawn bullets, some of them are missing, and when i log the position of the bullet in OnEnable, it shows a different position in the log than in the transform component implying that the bullet was taken from the already instanciated ones that are active. the longer the game runs, the worse this problem gets, and i have no idea what causes it.
i don’t use any multithreading in my game, and bullets are only spawned from coruntines or update loops.

using System;
using System.Collections.Generic;
using UnityEngine;

   public class ObjectPooler : MonoBehaviour
    {
        public static Dictionary<string, Queue<GameObject>> poolDictionary;
        public static Dictionary<string, List<GameObject>> instanciatedDictionary;


        [RuntimeInitializeOnLoadMethod]
        public static void RunOnStart()
        {
            instanciatedDictionary = new Dictionary<string, List<GameObject>>();
            poolDictionary = new Dictionary<string, Queue<GameObject>>();
        }

        public static GameObject InstanciateFromPool(string tag_, GameObject wantedInstance, Vector3 position, Quaternion rotation)
        {
            if (poolDictionary.ContainsKey(tag_))
            {
                if (poolDictionary[tag_].Count > 0)
                {
                    //take wanted object from list
                    GameObject instance = poolDictionary[tag_].Dequeue();

                    //set position, rotation, activate
                    instance.transform.position = position;
                    instance.transform.rotation = rotation;
                    instance.SetActive(true);

                    if (!instanciatedDictionary.ContainsKey(instance.tag))
                    {
                        //add to instanciated objects
                        instanciatedDictionary.Add(instance.tag, new List<GameObject>());
                    }
                    //add to instanciated list
                    instanciatedDictionary[instance.tag].Add(instance);

                    //Return
                    return instance;

                }
                else
                {
                    //instanciate
                    GameObject instance = Instantiate(wantedInstance, position, rotation);


                    if (!instanciatedDictionary.ContainsKey(instance.tag))
                    {
                        //add to instanciated objects
                        instanciatedDictionary.Add(instance.tag, new List<GameObject>());
                    }

                    //add to instanciated objects
                    instanciatedDictionary[instance.tag].Add(instance);

                    return instance;
                }
            }
            else
            {
                //create needed list
                poolDictionary.Add(tag_, new Queue<GameObject>());

                //spawn wanted object
                GameObject instance = Instantiate(wantedInstance, position, rotation);

                if (!instanciatedDictionary.ContainsKey(instance.tag))
                {
                    //add to instanciated objects
                    instanciatedDictionary.Add(instance.tag, new List<GameObject>());
                }
                instanciatedDictionary[instance.tag].Add(instance);

                return instance;
            }
        }
     

        public static void DestroyToPool(string tag_, GameObject gameObject)
        {
            if (poolDictionary.ContainsKey(tag_) && instanciatedDictionary.ContainsKey(gameObject.tag))
            {
                //deactivate
                gameObject.SetActive(false);

                //remove from instanciated
                instanciatedDictionary[gameObject.tag].Remove(gameObject);

                //add to list to reuse later
                poolDictionary[tag_].Enqueue(gameObject);
            }
            else
            {
                //create needed dictionarys
                if (!poolDictionary.ContainsKey(tag_))
                    poolDictionary.Add(tag_, new Queue<GameObject>());

                if (!instanciatedDictionary.ContainsKey(gameObject.tag))
                    instanciatedDictionary.Add(gameObject.tag, new List<GameObject>());

                //set inactive to reuse later
                gameObject.SetActive(false);

                //add to list to reuse later
                poolDictionary[tag_].Enqueue(gameObject);

                //remove from instanciated
                instanciatedDictionary[gameObject.tag].Remove(gameObject);


                throw new Exception("tag not found, new que created");
            }

        }

    }

In case you need to see how it is used, here is a basic tower that spawnes bullets (yes it is a PVZ bootleg)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using GeneralStuff;

public class FlyFungusAI : MonoBehaviour
{
    [Tooltip("Tag of the fired projectile")]
    public string tag_;

    [SerializeField] private RowFinder rowFinder;
    [SerializeField] private float cooldown, shakeIntensity, shakeDuration;
    [SerializeField] private GameObject projectile;
    [SerializeField] private Transform firePoint;
    [SerializeField] private Animator animator;
    [SerializeField] private ParticleSystem shootEffect;
    [SerializeField] private AudioClip sound;


    private float cooldownTimer;

    private int hashShoot;
    private void Awake()
    {
        hashShoot = Animator.StringToHash("Shoot");
    }

    private void Update()
    {
        cooldownTimer += Time.deltaTime;

        if (cooldownTimer > cooldown)
        {
            cooldownTimer = 0;
         

            if (EnemyFinder.ghoulInRow[rowFinder.row])
            {
                GameObject instance = ObjectPooler.InstanciateFromPool(tag_, projectile, firePoint.position, Quaternion.identity);


                StartCoroutine(ShootEffects());
            }

        }
    }

    private IEnumerator ShootEffects()
    {
        animator.SetBool(hashShoot, true);

        shootEffect.Play();

        CameraShake.Shake(shakeDuration, shakeIntensity);

        SoundManager.PlaySound(sound);

        yield return new WaitForSeconds(0.3f);

        animator.SetBool(hashShoot, false);
    }
}

I’m guessing that whatever bullet object you have, calls DestroyToPool?

it dosn’t seem to even spawn. when i log in the OnEnable function the postition of the bullet, when 8 bullets should be spawning, only 7 or 6 logs appear, all with different positions, but sometimes they don’t equal the actual position of the bullet that loged them

That didn’t really answer my question; I wanted to see your bullet code.

Also, does your code ever call the Exception?

The exception only gets called when i messed up the strings in the editor, for what i added it, or when i spawn enemys or bullets manually, when they get destroyed.

The bullet code for the paticular bullet i saw the problem most with:

using UnityEngine;
using System.Collections;
using GeneralStuff;

public class StandartProjectile : MonoBehaviour, ISavable
{
    [SerializeField] private Rigidbody2D rb;
    [SerializeField] private Vector2 projectileVelocity;
    [SerializeField] private float damage, destroyDelay;
    [SerializeField] private int pierce;

    [SerializeField] private bool destroyAfterDelay;

    [Tooltip("Tag of this gameobject")]
    [SerializeField] private string tag_;

    [SerializeField] private Collider2D col;
    [SerializeField] private SpriteRenderer spriteRenderer;

    [SerializeField] private AudioClip hitSound;

    private int pierce_;

    private void OnEnable()
    {
        if (destroyAfterDelay)
        {
            //revert Pseudo destroy
            col.enabled = true;
            spriteRenderer.enabled = true;
        }

        rb.velocity = projectileVelocity;
        pierce_ = pierce;

        Debug.Log(gameObject.transform.position.ToString() + " " + gameObject.name.ToString(), gameObject);
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.CompareTag("Ghoul"))
        {
            collision.gameObject.GetComponent<LifeSystem>().LoseLife(damage);

            pierce_--;

            SoundManager.PlaySound(hitSound);

            if (pierce_ < 0)
            {
                if (destroyAfterDelay)
                {
                    //Pseudo destroy
                    col.enabled = false;
                    rb.velocity = Vector2.zero;
                    spriteRenderer.enabled = false;
                    StartCoroutine(Destroy());
                }
                else
                {
                    ObjectPooler.DestroyToPool(tag_, gameObject);
                }
            }
        }
    }

    private IEnumerator Destroy()
    {
        yield return new WaitForSeconds(destroyDelay);

        ObjectPooler.DestroyToPool(tag_, gameObject);
    }

    [System.Serializable]
    private struct SaveData
    {
        public float xPos;
        public float yPos;

        public float zRotation;

        public float xVelocity;
        public float yVelocity;
    }

    public object SaveState()
    {
        return new SaveData()
        {
            xPos = transform.position.x,
            yPos = transform.position.y,

            zRotation = transform.rotation.z,

            xVelocity = rb.velocity.x,
            yVelocity = rb.velocity.y
        };
    }

    public void LoadState(object state)
    {
        var saveState = (SaveData)state;

        //Set position:

        transform.position = new Vector2(
            saveState.xPos,
            saveState.yPos
            );

        //Set rotation:

        rb.rotation = saveState.zRotation;

        //SetVelocity:

        rb.velocity = new Vector2(
            saveState.xVelocity,
            saveState.yVelocity
            );
    }
}

I didn’t really see any problems with the code, although it was a little redundant. I threw together all the scripts into a test project and it seems to all work fine for me. The problem might be that you didn’t set something up right, not that the code is necessarily wrong.

it seems like the 2 dictionarys, or at least some list in them aren’t accurate 100% of the time. at least some wiered bugs i have encountered in my game seem like something like this is causing them, like homing projectiles trying to hit already dead enemys, projectiles dissappearing and the counter for how many enemys are left being inaccurate sometimes.
i still havn’t figured out what could cause something like this, and i am not 100% certain that this is really the case.

do you have any idea what could cause such problems?

Anything can really cause any problems.

A better question is, “What is causing this problem today?”

Here is how you can find out!

What is often happening in these cases is one of the following:

  • the code you think is executing is not actually executing at all
  • the code is executing far EARLIER or LATER than you think
  • the code is executing far LESS OFTEN than you think
  • the code is executing far MORE OFTEN than you think
  • the code is executing on another GameObject than you think it is
  • you’re getting an error or warning and you haven’t noticed it in the console window

To help gain more insight into your problem, I recommend liberally sprinkling Debug.Log() statements through your code to display information in realtime.

Doing this should help you answer these types of questions:

  • is this code even running? which parts are running? how often does it run? what order does it run in?
  • what are the values of the variables involved? Are they initialized? Are the values reasonable?
  • are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

Knowing this information will help you reason about the behavior you are seeing.

If your problem would benefit from in-scene or in-game visualization, Debug.DrawRay() or Debug.DrawLine() can help you visualize things like rays (used in raycasting) or distances.

You can also call Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene manually, looking for all the parts, where they are, what scripts are on them, etc.

You can also call GameObject.CreatePrimitive() to emplace debug-marker-ish objects in the scene at runtime.

You could also just display various important quantities in UI Text elements to watch them change as you play the game.

If you are running a mobile device you can also view the console output. Google for how on your particular mobile target, such as this answer or iOS: https://discussions.unity.com/t/700551 or this answer for Android: https://discussions.unity.com/t/699654

Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

Here’s an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

https://discussions.unity.com/t/839300/3

You must find a way to get the information you need in order to reason about what the problem is.