Unity チュートリアルのタワーディフェンステンプレートを触ってみる(43)

Unity チュートリアルのタワーディフェンステンプレートを触ってみる(42)ではそのステージで使用できるタワーを設定するのに用いる TowerLibrary の解説を行った。今回は Agent の Wave を登録する Wave の継承関係にある TimedBehaviour について解説を行っていく。
1.タワーディフェンステンプレートのステージの設定編 – TimedBehaviour.cs
TimedBehaviour.cs について稚拙ながら解説
「TimedBehaviour.cs」は「Assets/Scripts/Core/Utilities/TimedBehaviour.cs」の指しておりスクリプトについては以下の通り。内容としては Timer のリストの管理を行っている。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68 using System.Collections.Generic;
using UnityEngine;
namespace Core.Utilities
{
/// <summary>
/// Abstract based class for helping with timing in MonoBehaviours
/// </summary>
public abstract class TimedBehaviour : MonoBehaviour
{
/// <summary>
/// List of active timers
/// </summary>
readonly List<Timer> m_ActiveTimers = new List<Timer>();
/// <summary>
/// Adds the timer to list of active timers
/// </summary>
/// <param name="newTimer">the timer to be added to the list of active timers</param>
protected void StartTimer(Timer newTimer)
{
if (m_ActiveTimers.Contains(newTimer))
{
Debug.LogWarning("Timer already exists!");
}
else
{
m_ActiveTimers.Add(newTimer);
}
}
/// <summary>
/// Removes timer from list of active timers
/// </summary>
/// <param name="timer">the timer to be removed from the list of active timers</param>
protected void PauseTimer(Timer timer)
{
if (m_ActiveTimers.Contains(timer))
{
m_ActiveTimers.Remove(timer);
}
}
/// <summary>
/// Resets and removes the timer
/// </summary>
/// <param name="timer">the timer to be stopped</param>
protected void StopTimer(Timer timer)
{
timer.Reset();
PauseTimer(timer);
}
/// <summary>
/// Iterates through the list of active timers and ticks
/// </summary>
protected virtual void Update()
{
for (int i = m_ActiveTimers.Count - 1; i >= 0; i--)
{
if (m_ActiveTimers[i].Tick(Time.deltaTime))
{
StopTimer(m_ActiveTimers[i]);
}
}
}
}
}
20行目 : 「protected void StartTimer(Timer newTimer)」はグローバル変数である m_ActiveTimers に対してタイマーの追加を行っている。
36行目 : 「protected void PauseTimer(Timer timer)」はグローバル変数である m_ActiveTimers に引数のタイマーがあれば、m_ActiveTimers から削除を行っている。
48行目 : 「protected void StopTimer(Timer timer)」は引数の Timer を Reset 後、PauseTimer の処理を行っている。
57行目 : 「protected virtual void Update()」は Unity 固有の更新処理を行っている。内容としてはすべての Timer リストに経過時間を伝え、Timer の経過処理に達していれば StopTimer の処理を行っている。
スポンサーリンク