[SOLVED] Uncaught TypeError: Cannot read properties of undefined (reading 'assets')

For some reason, when I try to create a new player (because the game is going to be multiplayer), I see that the code gets caught up on this for whatever reason.

Here is the project:
https://playcanvas.com/editor/scene/1417341

Open up two windows, on the first one you will see the error.
Thank you to anyone for their time in helping me! I hope this is just a simple error.

Hello @Kurios,

You may wanna add this keyword at the end of your method like this:

    this.socket.on('playerJoined', function(data){
        template = this.app.assets.get(83955491);
        var entity = template.resource.instantiate();
        entity.name = data.id;
        entity.setPosition(data.x, 1, data.y);
        this.app.root.addChild(entity);
    }, this);

Oddly, that did not do the trick, @Christina. Thank you for trying to help though.

Ah right!! I see that this.socket isn’t a PlayCanvas class instance, that means setting the context will not work like that. You should use a regular JavaScript bind like this:

    this.socket.on('playerJoined', function(data){
        template = this.app.assets.get(83955491);
        var entity = template.resource.instantiate();
        entity.name = data.id;
        entity.setPosition(data.x, 1, data.y);
        this.app.root.addChild(entity);
    }.bind(this));
2 Likes

Also, a small advice if I may.

We usually avoid using this.app.assets.get(83955491); method to get assets within our project. This may cause some issues. For example, if you fork the project these asset’s ids will change and your code will break. For example, in your current project this returns undefined

image

Using assets.find() method to find an asset by each name is the common way to do this to avoid issues like these.

https://developer.playcanvas.com/api/pc.AssetRegistry.html#find

3 Likes

Thank you again @Christina!
There are no more errors.

1 Like