Home > Software design >  C# (Galaga Style Project) - Limit Projectile Prefab Clones based on Hierarchy
C# (Galaga Style Project) - Limit Projectile Prefab Clones based on Hierarchy

Time:11-21

I am trying to practice creating a clone of Galaga following the same ruleset as the original. I am currently stuck trying to attempt a limit on the amount of cloned prefabs that can be in the scene at any one time, in the same way that Galaga's projectiles are limited to 2 on screen at any time. I want to make it so the player can shoot up to two projectiles, which destroy after 2 seconds or when they collide (this part is functioning), followed by not being able to shoot if two projectile clones are active and not yet destroyed in the hierarchy (Not working as I can instantiate projectiles over the limit of 2).

I have combed through Google for about 3 hours with no solutions that have worked for me, at least in the ways that I had attempted to implement them.

Thank y'all so much for the help!

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;
            }

        }
    }
}

CodePudding user response:

You could change the logic up a bit. An instance of the playerController class is active as long as the game is active, so it will know and retain the value of 'maxBullets' until you die or exit the program. So instead, every time you click "z", the first thing you should do is run the check. If the current amount of live projectiles equals the maximum, have the logic 'return' and exit out of the method.

  • Related