I have issues with creating an entity programmatically

Hello! I have struggling with something really basic today. Spawning an enemy programmatically. Sadly, I hit a wall with an ‘Uncaught TypeError’. I hope somebody here can help me find the issue.

Here is the error:

Uncaught TypeError: Cannot read property 'root' of undefined
    at Object.Network.createBoard (network.js?id=12072899:18)
    at r.<anonymous> (network.js?id=12072899:28)
    at r.emit (socket.js?id=12033828:8)
    at r.onevent (socket.js?id=12033828:9)
    at r.onpacket (socket.js?id=12033828:9)
    at r.<anonymous> (socket.js?id=12033828:9)
    at r.emit (socket.js?id=12033828:8)
    at r.ondecoded (socket.js?id=12033828:8)
    at a.<anonymous> (socket.js?id=12033828:9)
    at a.r.emit (socket.js?id=12033828:8)

Here is the .js code:

var Network = pc.createScript('network');
this.socket = io.connect('https://pongmmo.glitch.me');

var BoardMaterial;
var Boards = [];

// initialize code called once per entity
Network.prototype.initialize = function() {
    BoardMaterial = this.app.assets.get(12073995).resource;
};

Network.prototype.createBoard = function (boardData) {
    var boardEntity = new pc.Entity();
    boardEntity.addComponent("model", {type: 'box'});
    boardEntity.model.model.meshInstances[0].material = BoardMaterial;
    boardEntity.setPosition(boardData.X * 1000, 0, boardData.Y * 1000);
    boardEntity.setLocalScale(1000, 1, 1000);
    this.app.root.addChild(boardEntity);
    Boards.push(boardEntity);
};

socket.on ('boardAdd', function (BoardObject) {
    console.log('boardAdd received');
});

socket.on ('boardData', function (boardsData) {
    for (var index = 1; index < boardsData.length; index++)
        Network.prototype.createBoard(boardsData[index]);
});

The error is point at this line of code:

this.app.root.addChild(boardEntity);

Thank you!

Hi.

Can’t you share us your project?

Probably have to check is this.app available currently.

I can share the project…I am not sure how.

Will this link do?

https://playcanvas.com/project/548909/overview/pongmmo

I think what happens is that you lose context of the playcanvas app when calling it from inside a socket function.

Try to create a var called app and assing it (app = this.app) on Network.prototype.initialize, then remove “this.” from the line that’s giving you problems.

Don’t resolve assets by Id please. It breaks when somebody fork your projects.

Fixed - https://playcanvas.com/project/549787/overview
I left some comments there.

You lost your context, that’s right.

1 Like

Thank you very much!