敵の作成④(クラスの継承:HP)

クラスの継承
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyA : EnemyBase // ←ここを「EnemyBase」に変更する(これでEnemyBaseクラスを「継承」する)
{
void Start()
{
// EnemyBaseを「継承」しているので、そこで定義されている「HP」変数を使うことができる。
HP = 5;
}
}




Missileスクリプト
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Missile : MonoBehaviour
{
public GameObject effectPrefab;
private void OnTriggerEnter(Collider other)
{
// ★テクニック
// TryGetComponentはoutの後ろで指定したコンポーネント(スクリプト)を持っているか否かを判定できる。
// 「クラス継承」の場合、「スーパークラス」まで辿ることができる。
// (条件)もしも、ミサイルにぶつかった相手方がEnemyBaseを持っているならば・・・
if (other.TryGetComponent(out EnemyBase enemy))
{
// TakeDamage()メソッドを呼び出す。
// 「1」はこのミサイルのパワー
enemy.TakeDamage(1);
// ミサイルを破壊する。
Destroy(gameObject);
GameObject effect = Instantiate(effectPrefab, transform.position, Quaternion.identity);
Destroy(effect, 1.0f);
}
}
}


【2021版】Danmaku(基礎/全55回)
他のコースを見る
クラスの継承
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyA : EnemyBase // ←ここを「EnemyBase」に変更する(これでEnemyBaseクラスを「継承」する)
{
void Start()
{
// EnemyBaseを「継承」しているので、そこで定義されている「HP」変数を使うことができる。
HP = 5;
}
}




Missileスクリプト
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Missile : MonoBehaviour
{
public GameObject effectPrefab;
private void OnTriggerEnter(Collider other)
{
// ★テクニック
// TryGetComponentはoutの後ろで指定したコンポーネント(スクリプト)を持っているか否かを判定できる。
// 「クラス継承」の場合、「スーパークラス」まで辿ることができる。
// (条件)もしも、ミサイルにぶつかった相手方がEnemyBaseを持っているならば・・・
if (other.TryGetComponent(out EnemyBase enemy))
{
// TakeDamage()メソッドを呼び出す。
// 「1」はこのミサイルのパワー
enemy.TakeDamage(1);
// ミサイルを破壊する。
Destroy(gameObject);
GameObject effect = Instantiate(effectPrefab, transform.position, Quaternion.identity);
Destroy(effect, 1.0f);
}
}
}


敵の作成④(クラスの継承:HP)