敵を全滅させた時にゲームクリアの演出をしたい場合や、ブロック崩し等で自分の持ち玉が0になったらゲームオーバーにしたい時があると思います。
今回はそういう時にどうすればいいかを紹介していきます。
FindGameObjectsWithTagで検索する
素材
敵1
敵2

攻撃

ゲームクリア画像

例:敵を全員倒した場合、次の処理を行う
前提:
敵オブジェクトにはEnemyタグとRigidbody2DとBoxCollider2Dがついている
ゲームクリア画像のオブジェクトが敵オブジェクトのインスペクターにアサインされているゲームクリア画像のオブジェクトはオブジェクトのチェックボックスが外れている(SetActiveがFalseの状態)
ATKタグのついたオブジェクトにはBoxCollider2Dがついている
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyScript : MonoBehaviour
{
int HP;
int o;
public GameObject kusudama;
public void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("ATK"))
{
Damage();
}
}
public void Damage(){
HP-=1;
//HPが0になった場合
if(HP<=0){
GameObject[] objs= GameObject.FindGameObjectsWithTag("Enemy");//Enemyタグを検索する
foreach (GameObject obj in objs){
o++;
}
if(o<=1){//
Debug.Log("GameClear");
kusudama.SetActive(true);
}
}
Destroy(this.gameObject);
}
}



ATKタグのついたオブジェクトに当たると消滅し、最後の一個が消える時にクリア演出を行うようになっています。
コメント