c# - 试图创建一个对象池但在我的堆栈上获得空引用异常
问题描述
我正在尝试使用对象池来跟踪并在基于回合的生存游戏中生成敌人,这是我上学期开始上课的。自从我查看该项目以来已经有大约 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); 方法中的前两行被触发,在控制台中我收到一条消息,说我的敌人正在被添加回池中,但随后控制台中也出现了一个空引用异常,并且没有产生新的敌人。任何帮助,将不胜感激
解决方案
inactive
已声明但从未在提供的代码中分配。
在Start
我建议添加的方法中inactive = new Stack<GameObject>();
推荐阅读
- jsonpath - 访问 JSON::Path numbers only key
- javascript - 如何列出 listUsers Cognito 身份服务提供者?
- r - Travis CI 在 R 包子目录中找不到头文件
- python - 如何使用没有年份的 datetime_range 创建每小时列表
- python - 为什么我的 python 变量在递归期间全局作用?
- javascript - 使用 agora.io 发布流
- python - 如何使用 urllib 解析 url 但在文本提示中输入多个 url?
- c# - 未处理的异常:System.OutOfMemoryException:'内存不足。'
- java - 是什么导致我在 RecyclerView 中滚动性能不佳?
- asp.net-mvc - 过滤器后的asp.net核心验证