C# (Galaga Style Project) - 基于层级限制射弹预制克隆

C# (Galaga Style Project) - Limit Projectile Prefab Clones based on Hierarchy

我正在尝试按照与原版相同的规则集创建 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;
            }

        }
    }
}

你可以稍微改变一下逻辑。只要游戏处于活动状态,playerController class 的实例就会处于活动状态,因此它将知道并保留 'maxBullets' 的值,直到您死亡或退出程序。 因此,每次单击“z”时,您应该做的第一件事就是 运行 检查。如果当前的活动射弹数量等于最大值,则逻辑 'return' 并退出该方法。