Firstborn/Assets/RPG Creation Kit/Scripts/BehaviourTrees/Nodes/Control Flow/SelectorNode.cs

136 lines
3.7 KiB
C#
Raw Normal View History

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using XNode;
using RPGCreationKit.BehaviourTree;
using UnityEditor;
namespace RPGCreationKit.BehaviourTree
{
[CreateNodeMenu("RPGCK_BehaviourTree/SelectorNode", order = 1)]
[System.Serializable]
public class SelectorNode : BTNode
{
[Output(ShowBackingValue.Never, ConnectionType.Multiple, TypeConstraint.None)] public BTNode outputs;
// Use this for initialization
protected override void Init()
{
base.Init();
}
[ContextMenu("Work")]
public override void ReorderChild()
{
List<NodePort> endPorts = GetOutputPort("outputs").GetConnections();
List<BTNode> nodes = new List<BTNode>();
for (int i = 0; i < endPorts.Count; i++)
nodes.Add((endPorts[i].node as BTNode));
nodes.Sort(SortInGraphYPos);
for (int i = 0; i < nodes.Count; i++)
{
BTNode btNode = nodes[i] as BTNode;
btNode.indexInSequence = i;
}
}
// Return the correct value of an output port when requested
public override object GetValue(NodePort port)
{
return null; // Replace this
}
public int sortbyindex(BTNode a, BTNode b)
{
return a.indexInSequence.CompareTo(b.indexInSequence);
}
public override NodeState Execute()
{
if (m_NodeState == NodeState.Success || m_NodeState == NodeState.Failure)
if (hasEvaluated == true)
return m_NodeState;
List<NodePort> endPorts = GetOutputPort("outputs").GetConnections();
List<BTNode> nodes = new List<BTNode>();
for (int i = 0; i < endPorts.Count; i++)
nodes.Add((endPorts[i].node as BTNode));
nodes.Sort(sortbyindex);
for (int i = 0; i < nodes.Count; i++)
{
switch((nodes[i] as BTNode).Execute())
{
case NodeState.Failure:
continue;
case NodeState.Success:
m_NodeState = NodeState.Success;
hasEvaluated = true;
return m_NodeState;
case NodeState.Running:
m_NodeState = NodeState.Running;
return m_NodeState;
default:
continue;
}
}
m_NodeState = NodeState.Failure;
hasEvaluated = true;
return m_NodeState;
}
public override void ReEvaluate()
{
if (m_NodeState != NodeState.Running)
{
base.ReEvaluate();
hasEvaluated = false;
List<NodePort> endPorts = GetOutputPort("outputs").GetConnections();
for (int i = 0; i < endPorts.Count; i++)
{
(endPorts[i].node as BTNode).ReEvaluate();
}
}
}
public override void OnCreateConnection(NodePort from, NodePort to)
{
base.OnCreateConnection(from, to);
#if UNITY_EDITOR
EditorApplication.delayCall += ReorderChild;
#endif
}
public override void OnRemoveConnection(NodePort port)
{
base.OnRemoveConnection(port);
if (port.fieldName == "input")
indexInSequence = -1;
else if (port.fieldName == "outputs")
{
#if UNITY_EDITOR
EditorApplication.delayCall += ReorderChild;
#endif
}
}
public override void OnStart()
{
}
}
}