Spawn objects and access them from another object script

Hey defold comuunity
this is the first time i start with defold and lua programming so i wanted to know few things
for starting :
how to spawn an object in random places ,
after that access to all that spawend object from another object (script) and destroy them for example when they are bigger to an y value , thanks a lot requesting to this will help me get started and understading how things are in this engine and translate my knowlodge in game dev to this one ,

in another way i wanted to know how to access for each game object of a certain type from another script

thanks in advance

You’ve probably noticed that spawned objects get generated IDs so you can’t really write out their address like you would with preset objects. It’s hard to access them “out of the blue”, so you will want to store their URL somewhere. Generally either the script that spawned the new object will remember the URL, or a script on the spawned object itself will communicate its URL to any other objects that need it.

You can also get any object’s address through collision messages (if it has a collision object component). So for your example, if you want to destroy any objects that rise above a certain Y value, one method is to place a game object with ‘trigger’ collision at the top of your game area. It will get messages when any other objects with collision enter it, so you can destroy them.

If you want to track various groups of spawned objects, and access those groups from multiple places, I suggest you make a Lua module to manage this. I have a fairly simple one that you could try, or just write your own. Objects tell the module when they spawn and are destroyed (which adds and removes them from the list for their group), and then any other objects can access the group lists through the module.

2 Likes