[C#] foreach, lists and objects :D

Okay, here we go…
I have a list of classes:
I used {} because it thinks that those are the HTML tags so it doesn’t show the <>

List{Node} nodeList = new List{Node}();

And once I press the button I add new Start Node:

if(Input.GetKeyUp(KeyCode.P)){
    // first argument is IDCounter so that every node has unique ID;
	nodeList.Add(new StartNode(++nodeCounter, 10, 10));
}

So far, so good. Then I put some code to add another type of node.
Now, every node has overrided method NodeLogic which has Debug.Log(NodeID); which is just counter. And in order for me to run this method I used foreach loop…

foreach (Node node in nodeList) {
	node.NodeLogic();
}

but on Log its quite interesting:

--:Break:--
Start1
--:Break:--
Start2
Start2
--:Break:--
Start3
Start3
Start3
--:Break:--
Start4
Start4
Start4
Start4

When it should be:

--:Break:--
Start1
--:Break:--
Start1
Start2
--:Break:--
Start1
Start2
Start3

What it seems like that it counts how many objects there are in list and print out the ID of the last added Node that number of time.
Or is it how Objects work.

EDIT: I added some more code.

    //------Class that holds all the variables
	//List Holding Nodes
	List<Node> nodeList = new List<Node>();
	//Id Counter
	private int nodeCounter = 0;

// StartNode Class

using UnityEngine;
using System.Collections;

public class StartNode : Node {
	public StartNode(int IDcounter, float x, float y):base(IDcounter, x, y, "Start", 0, 1, true){
	}
	public override void NodeLogic(){
		Debug.Log(NodeID);
	}
	public override void BaseNodeDraw ()
	{
		base.BaseNodeDraw ();
	}
}
//---------This is parent constructor
public Node(int IDcounter, float x, float y, string NodeN, int NumInCh, int NumOutCh, bool activ){
		NodeName = NodeN;
		InputChannel = new string[NumInCh];
		OutputChannel = new string[NumOutCh];
		xPos = x;
		yPos = y;
		nodeWindow = new Rect(x,y,50,50);
		activated = activ;
		NodeID = string.Format("{0}{1}",NodeName,IDcounter);
	}

how about you show us your NodeLogic function

–

Yeah, how have you defined a 'Node'?

–

We need to see the complete code for NodeLogic, the definition of nodeID, and the code for the StartNode constructor, before this question can be answered without wild guessing.

–

What about the declaration of NodeID? Where is it, and is it static, as @Rudy suggests?

–

NodeID is just a string as you can see: public string NodeID; And then i declare it in base Node class with: NodeID = string.Format("{0}{1}",NodeName,IDcounter);

–

1 Answer

1

You probably have a “static” keyword added to whatever variable holds the node’s index.