13日目 前半 外部の関数の取得、敵の撃破(Destroy)

Aのとき(クリックした時)にB の関数が呼ばれるようにするには>

 

A

public class EnemyManager : MonoBehaviour

public void OnTap()
    {
        Debug.Log("クリックしました");
    }

 

B

void PlayerAttack()
    {
        player.Attack(enemy);
        enemyUI.UpdateUI(enemy);
    }

 

Aに

using System;

Action tapAction; //クリックした時に実行したい関数(外部から設定したい)
public void AddEventListenerOnTap(Action action) //tapActionに関数を登録する
    {
        tapAction += action;  //引数としてPlayerAttackを受け取っている
    }

public void OnTap()
    {        
        tapAction();
    }

 

Bに

public void Setup(EnemyManager enemyManager)
    {

        enemy.AddEventListenerOnTap(PlayerAttack); //PlayerAttackを引数として関数を使う→上のtapActionに加える
    }

 

<敵の撃破(Destroy)>

void PlayerAttack()  //攻撃時の関数
    {
        player.Attack(enemy);
        enemyUI.UpdateUI(enemy);
        if(enemy.hp == 0) //簡単なif文で、撃破時と相手のターンに分岐させる
        {
            Destroy(enemy.gameObject); //hpが0の時、ゲームオブジェクトの消滅
            EndBattle();
        }
        else
        {
            EnemyTurn();
        }
    }

 

void EnemyTurn()
    {
        enemy.Attack(player);
        playerUI.UpdateUI(player);
    }

 

void EndBattle()
    {
        Debug.Log("ゲーム終了");
    }