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

Unity チュートリアルのタワーディフェンステンプレートを触ってみる(33)ではレベルデータを保持している LevelList の解説を行った。今回は NavigationNodes に追加した Node について解説を行っていく。
1.タワーディフェンステンプレートのステージの設定編 – Node.cs
Node.cs について稚拙ながら解説
「Node.cs」は「Assets/Scripts/TowerDefense/Nodes/Node.cs」の指しておりスクリプトについては以下の通り。内容としては次の Node の取得及び設定を行っている。
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86 using TowerDefense.Agents;
using TowerDefense.MeshCreator;
using UnityEngine;
namespace TowerDefense.Nodes
{
/// <summary>
/// A point along the path which agents will navigate towards before recieving the next instruction from the NodeSelector
/// Requires a collider to be added manually.
/// </summary>
[RequireComponent(typeof(Collider))]
public class Node : MonoBehaviour
{
/// <summary>
/// Reference to the MeshObject created by an AreaMeshCreator
/// </summary>
[HideInInspector]
public AreaMeshCreator areaMesh;
/// <summary>
/// Selection weight of the node
/// </summary>
public int weight = 1;
/// <summary>
/// Gets the next node from the selector
/// </summary>
/// <returns>Next node, or null if this is the terminating node</returns>
public Node GetNextNode()
{
var selector = GetComponent<NodeSelector>();
if (selector != null)
{
return selector.GetNextNode();
}
return null;
}
/// <summary>
/// Gets a random point inside the area defined by a node's meshcreator
/// </summary>
/// <returns>A random point within the MeshObject's area</returns>
public Vector3 GetRandomPointInNodeArea()
{
// Fallback to our position if we have no mesh
return areaMesh == null ? transform.position : areaMesh.GetRandomPointInside();
}
/// <summary>
/// When agent enters the node area, get the next node
/// </summary>
public virtual void OnTriggerEnter(Collider other)
{
var agent = other.gameObject.GetComponent<Agent>();
if (agent != null)
{
agent.GetNextNode(this);
}
}
#if UNITY_EDITOR
/// <summary>
/// Ensure the collider is a trigger
/// </summary>
protected void OnValidate()
{
var trigger = GetComponent<Collider>();
if (trigger != null)
{
trigger.isTrigger = true;
}
// Try and find AreaMeshCreator
if (areaMesh == null)
{
areaMesh = GetComponentInChildren<AreaMeshCreator>();
}
}
void OnDrawGizmos()
{
Gizmos.DrawIcon(transform.position + Vector3.up, "movement_node.png", true);
}
#endif
}
}
17行目 : 「[HideInInspector]」は Inspector 上に表示しないことを指す決まり文句である。
29行目 : 「public Node GetNextNode()」は次のノードの取得を行っている。内容としては NodeSelector があれば、NodeSelector から次のノードを取得してる。
43行目 : 「public Vector3 GetRandomPointInNodeArea()」は メッシュからランダムな地点のポイントを取得している。
52行目 : 「public virtual void OnTriggerEnter(Collider other)」は Unity 固有の他の Collider がこのゲームオブジェクトの Collider に入った時の処理を行っている。内容としては入ってきた Collider が Agent であれば、 次のノード度としてこのゲームオブジェクトを設定している。