Setting a mesh from a script

Hi

I imported few meshes, now I’d like to switch mesh visible in the scene from the script. I can do this with standard geometry meshes:

this.entity.removeComponent('render');
this.entity.addComponent('render', {meshInstances: [new pc.MeshInstance(pc.createCylinder(), this.app.scene.material)]});

But I don’t know how to use an imported fbx instead of creating the shape with pc.createCylinder()

I guess, it should be something similar to:

    this.entity.addComponent("model", {
        type: "asset",
        asset: "box.fbx/Cube"
    });

But this did not work. How can I do this?

Regards

Hi @p4vv37,

If it’s an imported asset you need to assign the asset/assetID to that property, instead of a string path:

// --- get a reference to the render asset e.g. using its name
const asset = this.app.assets.find('Cube');

    this.entity.addComponent("model", {
        type: "asset",
        asset: asset.id
    });
2 Likes

Thank you.

I tried it, but I’m getting this error now:

asset.resource.clone is not a function

Maybe I’m using the wrong asset? Do you know about any example I could refer to?

Hi @p4vv37,

I don’t remember an example out of my head. Try sharing your project, if possible, so we can take a look. It may be easier to fix there.

Hi

Sure, it’s extremely simple, as I just wanted to check the basics.

There’s a pulse.js script:

var Pulse = pc.createScript('pulse');

Pulse.prototype.initialize = function() {
    this.factor = 0;
    this.meshId = 0;
};

Pulse.prototype.pulse = function () {
    this.factor = 1;
    const asset = this.app.assets.find('cone');
    this.app.assets.load(asset);

    this.entity.addComponent("model", {
        type: "asset",
        asset: asset.id
    });


};

// update code called every frame
Pulse.prototype.update = function(dt) {
    if (this.factor > 0) {
        this.factor -= dt * 2;
        var s = 1 + Math.sin(this.factor * 10) * this.factor * 0.5;
        this.entity.setLocalScale(s, s, s);
    } 
};

with
Pulse.prototype.pulse
That fires upon click, object pulses and I’m trying to replace a mesh in it

Regards

I forgot about the link :sweat:
https://playcanvas.com/project/936571/overview/wave-function-collapse

Looking at the project, you are mixing the legacy model component and newer render component.

I’ve made both the boxes use render components and on pulse, change the type from box to mesh, and assigned the render asset of yzxx to it

Pulse.prototype.pulse = function () {
    this.factor = 1;

    const asset = this.app.assets.find('yzxx');
    this.app.assets.load(asset);
    this.entity.render.type = 'asset';
    this.entity.render.asset = asset;
};

https://playcanvas.com/project/938489/overview/f-wave-function-collapse

1 Like

Thank you! it works great