如何在2D游戏中正确设置对象池



我的2D游戏在Unity中的对象池有几个问题,炮弹在与墙壁碰撞时不想停下来,其中1个爆炸射击,另9个一起射击,彼此相连,我的大炮是现场的静态对象。有人能帮我或给我一些提示吗?

这是我的代码,3个脚本:

ObjectPooling.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObjectPooling : MonoBehaviour
{
public static ObjectPooling instance;
[SerializeField] public GameObject objectToPool;
private List<GameObject> cannonBalls = new List<GameObject>();
private int numberOfObjects = 20;

private void Awake()
{
instance = this;
}
// Start is called before the first frame update
void Start()
{
for (int i = 0; i < numberOfObjects; i++)
{
GameObject gameObject = Instantiate(objectToPool);
gameObject.SetActive(false);
cannonBalls.Add(gameObject);
}
}
// Update is called once per frame
void Update()
{

}

public GameObject GetCannonBallObject()
{
for (int i = 0; i < cannonBalls.Count; i++)
{
if (!cannonBalls[i].activeInHierarchy)
{
return cannonBalls[i];
}
}
return null;
}
}

Cannon.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Cannon : MonoBehaviour
{

[SerializeField] private Rigidbody2D rb;
[SerializeField] private GameObject cannonBall;
[SerializeField] private Transform cannonBallPosition;
void Start()
{
}
private void Update()
{
Fire();
}
private void Fire()
{
cannonBall = ObjectPooling.instance.GetCannonBallObject();
if(cannonBall != null)
{
cannonBall.transform.position = cannonBallPosition.position;
cannonBall.SetActive(true);
}
}
}

CannonBall.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CannonBall : MonoBehaviour
{
private float speed = 10f;
[SerializeField] private Rigidbody2D rb;
// Start is called before the first frame update
void Start()
{

}
// Update is called once per frame
void Update()
{
rb.velocity = Vector2.left * speed;
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("FloorAndWall"))
{
// Destroy(this.gameObject);
gameObject.SetActive(false);
}
}
}

为什么炮弹是静态的?你试过不把它标记为静态吗?此外,这个问题与对象池无关。确保对象处于启用状态时,所有组件都处于活动状态。最后,当使用刚体时,应该在FixedUpdate((中处理它们,而不是在Update((内处理它们。

最新更新