Clone() creates multiple clones instead of creating one

So I am making a survival game and I want trees to randomly spawn. I am just trying to clone one time but for some reason it clones multiple times.
Here is my code

var Addtrees = pc.createScript('addtrees');

// initialize code called once per entity
Addtrees.prototype.initialize = function() {
    var tree = this.entity;
    var treeClone = tree.clone();
    treeClone.setPosition(0, 5, 0);
    this.app.root.addChild(treeClone);
};

// update code called every frame
Addtrees.prototype.update = function(dt) {
    
};

Please help me fix this issue

When this entity is created, the first thing it does (because it’s in initialize) is to clone itself, then the clone does the same thing and it’s clone will do the same thing, etc.

You basically have a recursive loop.

To fix this, don’t clone itself in the initialize function.

2 Likes

So where do I clone it?

What’s the intention/outcome here? Without more context, my suggestion would be to do this from another script that is not on the entity you are trying to clone.

Just trying to clone a object

In which case, if you need it at the start on the initialise step, it should be done in a script on a different entity that you are cloning.

Otherwise, you can do the clone on the action you are intending to do it in. Eg a button press, when it collides with something, etc.

Can you give me some code in order to get the tree entity by a tag and then clone it?

API: Entity | PlayCanvas API Reference

Untested so may have syntax errors

var treeEntities = this.app.root.findByTag('someTag');
if (treeEntities.length > 0) {
  var treeClone = treeEntities[0].clone();
  treeClone.setPosition(0, 5, 0);
  treeEntities[0].parent.addChild(treeClone);
};

To add on to what @yaustar said, findOne might be another good way of getting the first entity with a certain tag.

var node = this.app.root.findOne('tag', 'someTag');

You can then clone it similarly.

1 Like