[SOLVED] Setting Sprite on UI Image Element Via Script

I am struggling with assigning a sprite to an Image element using a script. I am pulling in a sprite through an attribute on the script, like so:

MyScript.attributes.add('myAttributeSprite', {type: 'asset', assetType: 'sprite'}); 

When I assign the sprite to the image element,

this.myEntity.element.sprite = this.myAttributeSprite;

I get this error in the console:

Which is pointing to this chunk in the engine:

  Object.defineProperty(ImageElement.prototype, "sprite", {get:function() {
    return this._sprite;
  }, set:function(value) {
    if (this._sprite === value) {
      return;
    }
    if (this._sprite) {
      this._unbindSprite(this._sprite);
    }
    if (this._spriteAsset) {
      var spriteAsset = this._system.app.assets.get(this._spriteAsset);
      if (spriteAsset && spriteAsset.resource !== value) {
        this.spriteAsset = null;
      }
    }
    this._sprite = value;
    if (this._sprite) {
      this._bindSprite(this._sprite);
      if (this._textureAsset) {
        this.textureAsset = null;
      }
    }
    if (this._sprite && this._sprite.atlas && this._sprite.atlas.texture) {
      this._renderable.setParameter("texture_emissiveMap", this._sprite.atlas.texture);
      this._renderable.setParameter("texture_opacityMap", this._sprite.atlas.texture);
    } else {
      this._renderable.deleteParameter("texture_emissiveMap");
      this._renderable.deleteParameter("texture_opacityMap");
    }
    if (this._sprite) {
      this._spriteFrame = pc.math.clamp(this._spriteFrame, 0, this._sprite.frameKeys.length- 1);
    }
    this._updateSprite();
  }});

The _sprite.frameKeys in the second to last line is where the problem comes in. Not sure how I can get the Image element to recognize this is a simple sprite with 1 frame. I tried many different avenues and can’t seem to work around this issue.

Thanks!

Hi @Travis,

Try doing the assignment like this:

this.myEntity.element.sprite = this.myAttributeSprite.resource;
2 Likes

Ah, perfect! I feel like I’ve run into this before with a texture as well. Is this explained somehwere in the documentation? I’d like to know what I’m tapping into when I do this.

Yes, so when you add attributes of type: asset on any script what you get returned is a reference to pc.Asset.

Here are the class docs:

https://developer.playcanvas.com/en/api/pc.Asset.html

A pc.Asset is a class responsible for wrapping with useful properties/methods any of the Playcanvas supported resources. It’s basically responsible for loading/unloading it and ultimately making the resource available to the engine.

The actual resource is always available in the asset resource property.

Here is the relevant manual page which explains how script attributes work:

https://developer.playcanvas.com/en/user-manual/scripting/script-attributes/

1 Like

Great, thank you. The pc.Asset was the piece I wasn’t quite connecting in the chain.

2 Likes