Search code examples
loopsanylogicagent

Anylogic detecting and iterating through agents placed on another agent (main)


I created a custom agent, call it 'MyAgent' and compiled it into a library. A user now starts a new Anylogic project, drags and places a number of these 'MyAgent' instances (each as a single agent) onto the project window (main form). I now have another agent, also placed on main that executes an algorithm to do stuff with the agents placed on the project. For this it needs to "detect" how many of these agents the user dropped on his project (if at all), and then iterate through each of these "MyAgent" instances, doing stuff with them.

Something like:

for (int i=0;i<="number of 'MyAgent' instances on this"-1;i++) {
MyAgent thisinstance= "collection of 'MyAgent's".get(i);
thisinstance."property_I_would_like_to_modify"="new value";
thisinstance."call_a_function():"; 
}

My problem is how to find:

  1. "number of 'MyAgent' instances on this" - on this form(Agent) that the user has dropped, might be nothing, may be 50, i don't know whether user dropped any, and if he did how many
  2. "collection of 'MyAgent's" - to allow me to iterate through the entire list

Above pretty simple. But may be entirely wrong approach. Could someone please offer some guidance on how to do this?


Solution

  • here is the only way to do this. On startup of your MyAgent (or on startup of your user's Main, if possible), run this function:

    int counter = 0;
    for (Object currObject : ((Agent)getRootAgent()).getEmbeddedObjects()) {
        if (currObject instanceof MyAgent) {
                counter ++;
        }
    }