Marc-Antoine Jacob
Marc-Antoine Jacob

Reputation: 95

How to deep look into all possible linked objects?

I'm having some headaches to figure out something I need to do programatically. Here's the basic code of my class.

public class Wire
{
    public List<Wire> connectedWires = new List<Wire>();

    //Example var we want to set
    public int i = 0;

    public void Initialize()
    {
   //Initialization code
   //Here we get all connected wires the actual one (this) and we put it in   connected wire
    }
}

I'm using this code with Unity, so I don't really know the execution order of the Initialize() methode of my Wire instances.

So creating some instances of Wire kinda builds a hierachy where all connected wires and sub-connected wires can be accessed with loops.

The problem I'm having is I want with a single instance of Wire, loop thought all possible connected wires and sub-connected wires, but I don't know how many Wire instances I have so it's impossible to "deep" iterate with imbricated foreach loops ! (foreac(){foreach(){... ?}})

How I would achieve that in a good way ?

Heres a reference picture for what is a wire. Wires

Upvotes: 0

Views: 72

Answers (1)

Cirano Eusebi
Cirano Eusebi

Reputation: 81

If wires are connected only once you can do something like this.

public class Wire
{
    public List<Wire> connectedWires = new List<Wire>();

    //Example var we want to set
    public int i = 0;

    public void Initialize()
    {
    //Initialization code
    //Here we get all connected wires the actual one (this) and we put it in   connected wire
    }
    public void LoopThroughWires()
    {
        //Do something with your wires or whatever
        i++;
        //Propagate to childs
        foreach(Wire wire on connectedWires)
        {
            wire.LoopThroughWires();
        }
    }
}

Beware that multiple connections to the same wire would end up calling the method multiple times.

You could use a visited flag to solve that issue.

Upvotes: 1

Related Questions