Accessing objects programmatically
When programming in and around CoppeliaSim, you will always need to reference scene objects. You do this with handles, that you obtain via sim.getObjectHandle, which expects an object name as input argument. For instance, from a plugin, you would access object Cuboid1 with:
From an embedded script, you would do it with:
Unassociated code is code that is not attached to any scene object. This includes all the code written for plugins, add-ons, remote API clients, external ROS nodes, external BlueZero nodes, and the main script.
In that case, object access is trivial as show following examples: you simply specify the object's full name in order to retrieve its handle:
// e.g. inside of a c/c++ plugin: int cuboid1Handle=simGetObjectHandle("Cuboid1"); // handle of object "Cuboid1" int cuboid2Handle=simGetObjectHandle("Cuboid2"); // handle of object "Cuboid2" int cuboid1Hash0Handle=simGetObjectHandle("Cuboid1#0"); // handle of object "Cuboid1#0"
# e.g. inside of a Python legacy remote API client: opMode=sim.simx_opmode_blocking res,cuboid1Handle=sim.simxGetObjectHandle(clientId,"Cuboid1",opMode) # handle of object "Cuboid1" res,cuboid2Handle=sim.simxGetObjectHandle(clientId,"Cuboid2",opMode) # handle of object "Cuboid2" res,cuboid1Hash0Handle=sim.simxGetObjectHandle(clientId,"Cuboid1#0",opMode) # handle of object "Cuboid1#0"
In that case, object access is a little bit more tricky, and this lies in the fact that associated code will be automatically duplicated if its associated object is duplicated (e.g. when you copy and paste a robot model for instance): in that case, will the copied code access the same objects as the original code?
Take the example of a child script attached to object Cuboid1 with following code:
What above code does is change the color of Cuboid1 to a random color. When you duplicate Cuboid1, the copy will be named Cuboid1#0. In that case the duplicated script remains identical to the original script, however the duplicated script will know that is must access Cuboid1#0 and not Cuboid1. And because of that, the copied cuboid will also change its color to a random color as did the original cuboid.
Duplicated scripts will also automatically access duplicated objects in order to guarantee a very good and easy scalability of a scene content. An automatic name index adjustment mechansim is used:
An object name can always be divided into a base name and a index part:
[Base name and index]
When associated code simply specifies the base name to retrieve the handle of an object, then CoppeliaSim will internally adjust the name by appending a hash character and the index of the object the script is associated with. If the full name is specified, then there is no automatic name adjustment:
[Automatic name adjustment mechanism for associated scripts]