【发布时间】:2021-12-30 10:21:42
【问题描述】:
我正在尝试按照与原始规则集相同的规则来练习创建 Galaga 的克隆。我目前正试图限制任何时候可以在场景中出现的克隆预制件的数量,就像 Galaga 的射弹在任何时候都限制在屏幕上的 2 个一样。我想要让玩家可以发射最多两个射弹,它们会在 2 秒后或它们碰撞时摧毁(这部分正在运行),然后如果两个射弹克隆都无法射击在层次结构中处于活动状态且尚未销毁(不工作,因为我可以实例化超过 2 个限制的射弹)。
我已经通过 Google 梳理了大约 3 个小时,但没有任何解决方案对我有用,至少在我尝试实施它们的方式上。
非常感谢大家的帮助!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class playerController : MonoBehaviour
{
public float moveSpeed = 1.0f;
public playerProjectile projectile;
public Transform launchOffset;
public int maxBullets = 0;
private GameObject cloneProjectile;
public Rigidbody2D player;
// Start is called before the first frame update
void Start()
{
player = this.GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
MovePlayer();
PlayerShoot();
}
public void MovePlayer()
{
player.velocity = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical")) * moveSpeed;
}
public void PlayerShoot()
{
if (Input.GetKeyDown(KeyCode.Z))
{
var cloneProjectile = Instantiate(projectile, launchOffset.position, launchOffset.rotation);
maxBullets++;
if (maxBullets >= 3)
{
Destroy(cloneProjectile, 0.1f);
maxBullets --;
return;
}
}
}
}
【问题讨论】:
-
我会使用对象池并使用大小为 2 的池。Unity 在这里写了一篇不错的教程learn.unity.com/tutorial/introduction-to-object-pooling。在 Unity 2021.1 及更高版本中,有一个内置的
ObjectPool(以及其他类似的类)可以提供帮助,但我不知道它是否能以您需要的方式处理您的最大问题。
标签: c# unity3d game-development