Unity チュートリアルのタワーディフェンステンプレートを触ってみる(27)
Unity チュートリアルのタワーディフェンステンプレートを触ってみる(26)ではエージェントに追加した DeathEffect について解説を行った。今回はエージェントに追加した LootDrop について解説を行っていく。
1.その他の効果、ビジュアライザー、挙動編 – LootDrop.cs
LootDrop.cs について稚拙ながら解説
「LootDrop.cs」は「Assets/Scripts/TowerDefense/Economy/LootDrop.cs」の指しておりスクリプトについては以下の通り。内容としては通貨のドロップ処理を行っている。
[cce_csharp]using Core.Health;
using TowerDefense.Level;
using UnityEngine;
namespace TowerDefense.Economy
{
/// <summary>
/// A class that adds money to the currency when the attached DamagableBehaviour dies
/// </summary>
[RequireComponent(typeof(DamageableBehaviour))]
public class LootDrop : MonoBehaviour
{
/// <summary>
/// The amount of loot/currency dropped when object "dies"
/// </summary>
public int lootDropped = 1;
/// <summary>
/// The attached DamagableBehaviour
/// </summary>
protected DamageableBehaviour m_DamageableBehaviour;
/// <summary>
/// Caches attached DamageableBehaviour
/// </summary>
protected virtual void OnEnable()
{
if (m_DamageableBehaviour == null)
{
m_DamageableBehaviour = GetComponent<DamageableBehaviour>();
}
m_DamageableBehaviour.configuration.died += OnDeath;
}
/// <summary>
/// Unsubscribed from the <see cref="m_DamageableBehaviour"/> died event
/// </summary>
protected virtual void OnDisable()
{
m_DamageableBehaviour.configuration.died -= OnDeath;
}
/// <summary>
/// The callback for when the attached object "dies".
/// Add <see cref="lootDropped"/> to current currency
/// </summary>
protected virtual void OnDeath(HealthChangeInfo info)
{
m_DamageableBehaviour.configuration.died -= OnDeath;
if (info.damageAlignment == null ||
!info.damageAlignment.CanHarm(m_DamageableBehaviour.configuration.alignmentProvider))
{
return;
}
LevelManager levelManager = LevelManager.instance;
if (levelManager == null)
{
return;
}
levelManager.currency.AddCurrency(lootDropped);
}
}
}[/cce_csharp]
26行目 : 「protected virtual void OnEnable()」は Unity 固有のこのオブジェクトが有効となったときの処理を行っている。内容としては DamageableBehaviour の状態が died になった時 OnDeath の処理を行うよう設定している。
38行目 : 「protected virtual void OnDisable()」は Unity 固有のこのオブジェクトが無効となったときの処理を行っている。内容としては DamageableBehaviour の状態が died になった時 OnDeath の処理を解除している。
57行目 : 「protected virtual void OnDeath(HealthChangeInfo info)」DamageableBehaviour の状態が died となったときの処理を定義している。内容としては DamageableBehaviour の状態が died になった時 OnDeath の処理を解除後、プレイヤーの所持している通貨に対してドロップする金額を追加している。