Create variables using gameObject.name

i’m trying to set my game up so it will automatically set up a pool for some weapon objects, then when my character picks up the gun, it will attempt to grab the items referenced on the guns from the appropriate pools when the gun is fired.

currently i’m using Resources.LoadAll to set up an array of Muzzle Flashes, Bullet Impacts and Bullet Tracers, this all works fine.

Now I need to create a pool for each object in those arrays, and I would like if possible for each pool variable name to be the gameObject.name

Heres the code so far:

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

public class BulletTracerPool : MonoBehaviour
{
    public GameObject[] muzzleFlashes;
    public GameObject[] bulletImpacts;
    public GameObject[] bulletTracers;


    void Start()
    {
        muzzleFlashes = Resources.LoadAll<GameObject>("Weapons/Weapon Muzzle Flashes");
        bulletImpacts = Resources.LoadAll<GameObject>("Weapons/Weapon Bullet Impacts");
        bulletTracers = Resources.LoadAll<GameObject>("Weapons/Weapon Bullet Tracers");

        foreach (GameObject flashes in muzzleFlashes)
        {
            var muzzleFlashesPool = new ObjectPool<GameObject>(() => new GameObject(this.gameObject.name), (obj) => obj.SetActive(true), (obj) => obj.SetActive(false), (obj) => Destroy(obj), false, 100, 200);
        }

        foreach (GameObject impacts in bulletImpacts)
        {
            // SETUP BULLET IMPACTS POOL
        }

        foreach (GameObject tracers in bulletTracers)
        {
            // SETUP BULLET TRACERS POOL
        }
    }
}

Once that’s done, when the gun fires it will simply look for a pool that matches the name of the desired effect, and grab one from the pool.

So I basically need muzzleFlashesPool to be gameObject.name , does anyone know how I would achieve this?.

Thanks in advance,
DPK

Yep, you can’t. You can’t rename variables in code at runtime. If your gameObject.name was, for example, “MuzzleFlashPoolSuperHolderOfDoom”, you can’t just have the variable suddenly be
var MuzzleFlashPoolSuperHolderOfDoom = new …

If that’s not what you meant, then please clarify. as I might be misunderstanding what you are actually doing.

If your gameobjects all have different names, I’d suggest using a dictionary and using the gameObject.name as the key. If you have some that are the same, this isn’t going to work since dictionaries must contain unique values for the keys.

1 Like

Thanks, i’ll look into a Dictionary then