How to create a new instance of an object?
I am trying to create a node system which is aware of its neighbours with an edge class. The code below is creating an error of NullReferenceExeption: Object reference not set to an instance of an object NodeScript.GenerateEdges() (at Assets/Scripts/NodeScript.cs:109).
public void GenerateEdges()
{
Collider[] neighbourNodes = Physics.OverlapBox(transform.position, transform.localScale);
int edgeNumber = 0;
foreach(Collider nodeCollider in neighbourNodes)
{
NodeScript node = nodeCollider.gameObject.GetComponent<NodeScript>();
if(node != null)
{
EdgeScript edge = new EdgeScript();
edge.SetFrom(this);
edge.SetTo(node);
edge.SetCost((node.transform.position - this.transform.position).magnitude);
edges.Add(edge); // <-- Error is on this line
++edgeNumber;
}
}
}
Here is the EdgeScript class as well:
public class EdgeScript {
private NodeScript from;
private NodeScript to;
private float cost;
public EdgeScript()
{
}
~EdgeScript()
{
}
public void SetFrom(NodeScript newFrom)
{
if (newFrom != null)
{
from = newFrom;
}
}
public void SetTo(NodeScript newTo)
{
if (newTo != null)
{
to = newTo;
}
}
public void SetCost(float newCost)
{
cost = newCost;
}}
What have I done wrong?
P.S. I realise I need Get functions in the EdgeScript I haven't finished the class yet.
Your answer
Follow this Question
Related Questions
How to hold and move a object using other object? 3 Answers
basic Questions about MeshFilter:Optimize mesh 1 Answer
How to add a script to a parent object and not every individual child object. 1 Answer
Does the sequence in which I keep the objects in a scene matter really? 1 Answer
How to check if any GameObject equals any other GameObject 0 Answers