How to instantiate an Agent via code in Anylogic

Viewed 84

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

2 Answers

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.

Certain functions are not available inside agents that get created programmatically, like the default random number generator and certain other utility functions that get passed to agents.

So if you do this for example it wont work, and you get an NPE (Null Pointer Exception)

enter image description here

Rather always make use of a population - unless you know you will not be using any of those internal functions.

MyAgent name = add_myAgents();

Where myAgents is a population.

Related