River Jiang
2020-10-27 1f5eda1c9d22a3676298751c7282a5874f13bed0
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
using Core.Extensions;
#if UNITY_EDITOR
using UnityEngine;
#endif
 
namespace TowerDefense.Nodes
{
    /// <summary>
    /// Randomly selects the next node
    /// </summary>
    public class RandomNodeSelector : NodeSelector
    {
        /// <summary>
        /// The sum of all Node weights in m_LinkedNodes
        /// </summary>
        protected int m_WeightSum;
 
        /// <summary>
        /// Gets a random node in the list
        /// </summary>
        /// <returns>The randomly selected node</returns>
        public override Node GetNextNode()
        {
            if (linkedNodes == null)
            {
                return null;
            }
            int totalWeight = m_WeightSum;
            return linkedNodes.WeightedSelection(totalWeight, t => t.weight);
        }
 
        protected void Awake()
        {
            // cache the linked node weights
            m_WeightSum = TotalLinkedNodeWeights();
        }
#if UNITY_EDITOR
        protected override void OnDrawGizmos()
        {
            Gizmos.color = Color.cyan;
            base.OnDrawGizmos();
        }
#endif
        /// <summary>
        /// Sums up the weights of the linked nodes for random selection
        /// </summary>
        /// <returns>Weight Sum of Linked Nodes</returns>
        protected int TotalLinkedNodeWeights()
        {
            int totalWeight = 0;
            int count = linkedNodes.Count;
            for (int i = 0; i < count; i++)
            {
                totalWeight += linkedNodes[i].weight;
            }
            return totalWeight;
        }
    }
}