对象池中我的 Get() 函数不断实例化更多对象。我找不到问题所在,没有错误。 这是 Spawner 类。
public class OPool : MonoBehaviour
{
public Bullet bulletPrefab;
public UnityEngine.Pool.ObjectPool<Bullet> _bulletPool;
public static OPool _OPool;
public void Start()
{
_bulletPool = new UnityEngine.Pool.ObjectPool<Bullet>(createFunc: InstantiatePoolBullet, actionOnGet: GetBulletFromPool,
actionOnRelease: ReturnBulletToPool,DestroyBullet, true, 15,20);
}
public void Update()
{
transform.position = transform.parent.position + new Vector3(0f, 3.5f, 2.5f);
}
public Bullet InstantiatePoolBullet()
{
Bullet bullet = Instantiate(bulletPrefab, transform);
bullet.SetPool(_bulletPool);
return bullet;
}
public void GetBulletFromPool(Bullet bullet)
{
bullet.transform.position = transform.position;
bullet.transform.rotation = transform.rotation;
bullet.gameObject.SetActive(true);
}
public void ReturnBulletToPool(Bullet bullet)
{
bullet.gameObject.SetActive(false);
}
public void DestroyBullet(Bullet bullet)
{
Destroy(bullet.gameObject);
}
}
这是我的子弹课
public class Bullet : MonoBehaviour
{
public float speed;
private ObjectPool<Bullet> _pool;
public float _deadtime = 0.7f;
private float _currentTime;
private Rigidbody rb;
public int damage;
public static Bullet bullet;
private void Awake()
{
rb = GetComponent<Rigidbody>();
_currentTime = _deadtime;
}
private void Start()
{
bullet = this;
ApplyVelocity();
}
private void Update()
{
if (_currentTime > 0)
{
_currentTime -= Time.deltaTime;
}
else
{
DestroyBullet();
}
}
public void SetPool(ObjectPool<Bullet> pool)
{
_pool = pool;
}
private void OnEnable()
{
ApplyVelocity();
_currentTime = _deadtime;
}
private void ApplyVelocity()
{
rb.velocity = speed * transform.forward;
}
private void DestroyBullet()
{
if (_pool != null)
{
_pool.Release(this);
}
else
{
Destroy(gameObject);
}
}
这就是我调用 Get 函数的地方,它位于 Player 脚本中。
void Update()
{
if (transform.IsChildOf(RunPlayer.Instance.transform) && RunPlayer.Instance._state == NumState.Running)
{
_State = State.Free;
}
if (_State == State.Free)
{
canShoot = true;
charAnim.SetBool(Starting, true);
StartCoroutine(ShootR());
}
}
public enum State
{
Idle,
Free
}
public IEnumerator ShootR()
{
while (canShoot)
{
if (downShootRate)
{
yield return new WaitForSeconds(.150f);
}
yield return new WaitForSeconds(.145f);
bulletPool._bulletPool.Get();
}
}
我只是编码新手,谢谢您花时间。对我有什么建议吗?我找不到问题。
我尝试过调试,寻找解决方案,但仍然如此。我希望我能找到它不断实例化的问题。
我的想法是,理性就是你的逻辑。 你可以回顾一下你的逻辑。 如果您有任何疑问,请联系我。
Skype id : 金慧 Skype 用户名 : live:.cid.d49a56ccc8f00388