NodeGraph.cs 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. using System;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. namespace XNode {
  5. /// <summary> Base class for all node graphs </summary>
  6. [Serializable]
  7. public abstract class NodeGraph : ScriptableObject {
  8. /// <summary> All nodes in the graph. <para/>
  9. /// See: <see cref="AddNode{T}"/> </summary>
  10. [SerializeField] public List<Node> nodes = new List<Node>();
  11. /// <summary> Add a node to the graph by type (convenience method - will call the System.Type version) </summary>
  12. public T AddNode<T>() where T : Node {
  13. return AddNode(typeof(T)) as T;
  14. }
  15. /// <summary> Add a node to the graph by type </summary>
  16. public virtual Node AddNode(Type type) {
  17. Node.graphHotfix = this;
  18. Node node = ScriptableObject.CreateInstance(type) as Node;
  19. node.graph = this;
  20. nodes.Add(node);
  21. return node;
  22. }
  23. /// <summary> Creates a copy of the original node in the graph </summary>
  24. public virtual Node CopyNode(Node original) {
  25. Node.graphHotfix = this;
  26. Node node = ScriptableObject.Instantiate(original);
  27. node.graph = this;
  28. node.ClearConnections();
  29. nodes.Add(node);
  30. return node;
  31. }
  32. /// <summary> Safely remove a node and all its connections </summary>
  33. /// <param name="node"> The node to remove </param>
  34. public virtual void RemoveNode(Node node) {
  35. node.ClearConnections();
  36. nodes.Remove(node);
  37. if (Application.isPlaying) Destroy(node);
  38. }
  39. /// <summary> Remove all nodes and connections from the graph </summary>
  40. public virtual void Clear() {
  41. if (Application.isPlaying) {
  42. for (int i = 0; i < nodes.Count; i++) {
  43. Destroy(nodes[i]);
  44. }
  45. }
  46. nodes.Clear();
  47. }
  48. /// <summary> Create a new deep copy of this graph </summary>
  49. public virtual XNode.NodeGraph Copy() {
  50. // Instantiate a new nodegraph instance
  51. NodeGraph graph = Instantiate(this);
  52. // Instantiate all nodes inside the graph
  53. for (int i = 0; i < nodes.Count; i++) {
  54. if (nodes[i] == null) continue;
  55. Node.graphHotfix = graph;
  56. Node node = Instantiate(nodes[i]) as Node;
  57. node.graph = graph;
  58. graph.nodes[i] = node;
  59. }
  60. // Redirect all connections
  61. for (int i = 0; i < graph.nodes.Count; i++) {
  62. if (graph.nodes[i] == null) continue;
  63. foreach (NodePort port in graph.nodes[i].Ports) {
  64. port.Redirect(nodes, graph.nodes);
  65. }
  66. }
  67. return graph;
  68. }
  69. protected virtual void OnDestroy() {
  70. // Remove all nodes prior to graph destruction
  71. Clear();
  72. }
  73. }
  74. }