Skip to content

Instantly share code, notes, and snippets.

@Problematic
Created August 31, 2014 20:42
Show Gist options
  • Save Problematic/a14aeb0638a09f378ad3 to your computer and use it in GitHub Desktop.
Save Problematic/a14aeb0638a09f378ad3 to your computer and use it in GitHub Desktop.
Node graph for Unity3D
using UnityEngine;
[System.Serializable]
public class Edge
{
public Edge()
{
}
public Edge(Node node, int cost)
{
this.node = node;
this.cost = cost;
}
public Edge(Node node) : this(node, 1)
{
}
[SerializeField]
Node
node;
public Node Node
{
get
{
return node;
}
}
[SerializeField]
int
cost;
public int Cost
{
get
{
return cost;
}
}
}
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
[ExecuteInEditMode]
public class Graph : MonoBehaviour, IEnumerable<Node>
{
[SerializeField]
GameObject
nodePrefab;
[SerializeField]
List<Node>
nodes;
void Awake()
{
nodePrefab.CreatePool();
}
public void AddNode(Node node)
{
node.Graph = this;
nodes.Add(node);
}
public void CreateNode(Vector3 position)
{
GameObject go = nodePrefab.Spawn(transform, position);
Node node = go.GetComponent<Node>();
AddNode(node);
}
public void AddDirectedEdge(Node from, Node to, int cost)
{
from.Edges.Add(new Edge(to, cost));
}
public void AddUndirectedEdge(Node from, Node to, int cost)
{
from.Edges.Add(new Edge(to, cost));
to.Edges.Add(new Edge(from, cost));
}
public List<Node> Nodes
{
get
{
return nodes;
}
}
public int Count
{
get
{
return nodes.Count;
}
}
public IEnumerator<Node> GetEnumerator()
{
return nodes.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
[ExecuteInEditMode]
public class Node : MonoBehaviour
{
[SerializeField]
Graph
graph;
public Graph Graph
{
get
{
return graph;
}
set
{
graph = value;
}
}
[SerializeField]
List<Edge>
edges;
public List<Edge> Edges
{
get
{
return edges;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment