Search code examples
anylogic

How to instantiate an Agent via code in Anylogic


I'm having an issue with Anylogic: I'm writing a function where I need to declare a new item of the type of an already existing Agent type. If I declare it with the code:

MyAgent name = new MyAgent();

everything is ok but when I try to execute a function to change the value of an internal value,

name.func();

it gives me a NullPointerException, because the internal variable of the declared MyAgent seems not to exist. What am I missing? Thanks a lot in advance for your help


Solution

  • When you have a population use the add_myAgents() method, but if you don't want to use a defined population you have to do this:

    MyAgent m=new MyAgent();
    m.createAndStart(anyAgent);
    m.lognormal(0.1,0.1,5);
    

    createAndStart does the magic for you.

    anyAgent can be actually any existing agent of your model (for example main), the population will still be created in the default population of your top-level agent, no matter what you put in there.