Object Creation from Prefab - Constructor Options

I’m working in Cocos Creator 1.6.1 and Typescript as script language.

I have created a simple ball prefab. I have attached a script to it. That script dictates the behaviors of instances of the ball.

I have a parent node that also has a script. That parent has a property for the prefab as well as instantiation for the multiple instances of the ball.

@property(cc.Prefab)
BallPrefab: cc.Prefab;

onLoad(): void {
    
    const ball1 = cc.instantiate(this.BallPrefab);
    const ball2 = cc.instantiate(this.BallPrefab);
    
   
    this.node.addChild(ball1);
    this.node.addChild(ball2);

    ball1.position = new cc.Vec2(100,100);
    ball2.position = new cc.Vec2(200,100);
}

I would like to do two things:

  1. Call initiazation code on the new instance (is there a concept of a constructor?)
  2. Call methods on the instantiated class (eg: ball1, ball2). This is not possible as both ball1 and ball2 are instances of Node and not of BallPrefab.

Any help would be appreciated.

There’s no concept of a constructor, but you can write a factory function to achieve like that.

function newBall(parent, position) {
    const ball = cc.instantiate(this.BallPrefab);
    ball.position = new cc.Vec2(100,100);
    parent.addChild(ball);
    return ball;
}

Further, you can also return a Ball component to call method like

function newBall(parent, position) {
    const ball = cc.instantiate(ballPrefab);
    ball.position = new cc.Vec2(100,100);
    parent.addChild(ball);
    return ball.getComponent('Ball');
}
var ball = newBall(this.node, new cc.Vec2(100, 100));
ball.play();