Unityでジャンクゲームを作っているっぽい

会社帰りにGPD PocketにUnity入れてゲーム作ってます

07 発射数の制限

画面内に発射できる弾数を制限したい

方針

  1. GameController.csで画面内の弾数をカウントして、発射flagを制御
  2. Player_Shot.csで↑のflagをみて、発射を制御

GameController.csで制御すれば、あとあとパワーアップとかで運用できそうだから

空のオブジェクトでGameControllerを作る

GameControllerというtagもアタッチする
f:id:mekatamatama:20201012224344p:plain

GameController.csを用意

ここで画面内の最大弾数を監視して、発射できるかどうか判定してフラグを制御

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GameController : MonoBehaviour{
	public int shotNum;	//画面内の弾数
	public int shotNumMax;	//画面内の弾数MAX
	public bool isShot;	//発射flag

	void Start(){
		shotNum = 0;		//初期化
		isShot = false;		//初期化
	}

	void Update(){
		//画面内の弾数で攻撃可能か判定
		if(shotNum >= shotNumMax){
			isShot = false;
		}
		if(shotNum < shotNumMax){
			isShot = true;
		}
	}
}

Player_Shot.csに追記

弾発射で、GameControllerで見ている画面内の弾数を加算

public class Player_Shot : MonoBehaviour{
	GameObject gameController;			//検索したオブジェクト入れる用
	public GameObject bulletObject = null;		//弾プレハブ
	public Transform bulletStartPosition = null;	//弾の発射位置を取得する

	void Start(){
		gameController = GameObject.FindWithTag ("GameController");	//GameControllerを探す
	}

	//bullet発射
	public void PlayerShot(){
		//gcって仮の変数にGameControllerのコンポーネントを入れる
		GameController gc = gameController.GetComponent<GameController>();
		if(gc.isShot){
			//弾を生成する位置を指定
			Vector3 vecBulletPos = bulletStartPosition.position;
			//弾を生成
			Instantiate(bulletObject, vecBulletPos, transform.rotation);
			//画面内の弾数を加算
			gc.shotNum ++;
		}
	}
}

Player_Bullet.cs

弾を消去したらGameControllerで見ている画面内の弾数を減らす

gameController系を追加
PlayerShot()内で、gc.isShotフラグを見て弾の発射を制御
弾を発射時に、画面内の弾数を加算

OnTriggerEnter( Collider other)内で、弾を消去する時に画面内の弾数を減算

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player_Bullet : MonoBehaviour{
	GameObject gameController;	//検索したオブジェクト入れる用
	public float speed = 0.0f;	//移動speed

	void Start(){
		gameController = GameObject.FindWithTag ("GameController");	//GameControllerを探す
	}

	void Update(){
		//移動
		transform.position += transform.up * speed * Time.deltaTime;
	}

	//他のオブジェクトとの当たり判定
	void OnTriggerEnter( Collider other) {
		if(other.tag == "Wall_Up"){
			//gcって仮の変数にGameControllerのコンポーネントを入れる
			GameController gc = gameController.GetComponent<GameController>();
			//画面内の弾数を減算
			gc.shotNum --;
			Destroy(gameObject);	//このGameObjectを[Hierrchy]ビューから削除する
		}
	}
}

画面内の弾数MAXを設定する

とりあえず、画面内に3発までだす
f:id:mekatamatama:20201012231213p:plain

こんな感じになりました
f:id:mekatamatama:20201012231345g:plain:h300