首页 > 解决方案 > 试图创建一个对象池但在我的堆栈上获得空引用异常

问题描述

我正在尝试使用对象池来跟踪并在基于回合的生存游戏中生成敌人,这是我上学期开始上课的。自从我查看该项目以来已经有大约 6 个月的时间了,而且我对使用堆栈和字典不是很有经验,所以我在诊断问题时遇到了麻烦。我已经摆弄了大约一个星期的东西,但一直无法找出问题所在,所以我想知道这里是否有人可以帮助我。

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

public class poolerScript : MonoBehaviour
{
    [System.Serializable]
    public class pool
    {
        public string tag;
        public GameObject prefab;
        public int size;
    }

    EntityHealth EntityHealth;
    public static poolerScript Instance;

    private void Awake()
    {
        Instance = this;
    }

    Stack<GameObject> inactive;
    public List<pool> pools;
    public Dictionary<string, Queue<GameObject>> poolDictionary;

    // Start is called before the first frame update
    void Start()
    {
        poolDictionary = 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);
            }

            poolDictionary.Add(pool.tag, objectPool);
        }
    }


    public GameObject spawnFromPool(string tag, Vector3 position, Quaternion rotation)
    {
        if (!poolDictionary.ContainsKey(tag))
        {
            Debug.LogWarning("Pool with tag " + tag + " does not exist");
            return null;
        }

        GameObject objectToSpawn = poolDictionary[tag].Dequeue();

        objectToSpawn.SetActive(true);
        objectToSpawn.transform.position = position;
        objectToSpawn.transform.rotation = rotation;

        iPooledObj pooledObj = objectToSpawn.GetComponent<iPooledObj>();

        if (pooledObj != null)
        {
            pooledObj.onObjectSpawn();
        }

        poolDictionary[tag].Enqueue(objectToSpawn);

        return objectToSpawn;
    }

    public void Despawn(GameObject obj)
    {
        obj.SetActive(false);

        Debug.Log($"Adding a(n) {obj.name} back to the pool.");
        inactive.Push(obj);
    }
}

我遇到的问题是在代码的最后一行 inactive.Push(obj); 方法中的前两行被触发,在控制台中我收到一条消息,说我的敌人正在被添加回池中,但随后控制台中也出现了一个空引用异常,并且没有产生新的敌人。任何帮助,将不胜感激

标签: c#

解决方案


inactive已声明但从未在提供的代码中分配。

Start我建议添加的方法中inactive = new Stack<GameObject>();


推荐阅读