Editor Script: How can I hook asset selection?

I am going to make own asset importer.
When user select one asset on editor, show parse button on Attribute panel.
It’s my code, but this don’t hook selection event.

editor.on('selection:toggle', function(item,options) {    console.log(item.get('name'), 'asset been added');});

Hi @Fan_Flex,

Studying the Editor API on the following link I can see there is an internal event fired on the Selection object:

Which you can leverage like this, just make sure to check if the item is an Asset, since it will fire for both assets and entities:

editor.selection.on('change', (items) => {
   console.log(items);
});

image

@yaustar @vaios may be able to comment if there is a public API for doing that.

1 Like

Thank you for your kind. :grinning_face_with_smiling_eyes:
It’s very helpful for me.

1 Like

@Leonidas Thank you for your help.
Below is my code. I want when I select *.act file, show the “Parse SPR” button on Attribute Panel.
But the button once appear and then immediately disappear. pls help me.

    function createParseButton() {
      
        const btn = new pcui.Button({ text: 'Parse SPR' });
        btn.style.position = 'realative';
         console.log("createParseButton");
        editor.call('layout.attributes').append(btn);

        let boxes;

        btn.on('click', () => {
            // delete existing boxes
            if (boxes) {
                editor.entities.delete(boxes);
                boxes = null;
            }

            generateBoxes(10, new pc.Vec3(), 10).then(result => {
                boxes = result;
            });
        });
    }
    
  function initialize(){
    
    editor.selection.on('add',function(item){
      console.log("asset is added");
      var item_name = item._observer.get('name');
      var re = /(?:\.([^.]+))?$/;
      var ext = re.exec(item_name)[1]; 
      console.log(ext == "act");
      ext == "act" && createParseButton();
    });
    createParseButton();
    
  }

I solved this problem.
I found when editor.selection.change or add event happen, attribute panel is cleared automatically.
Hook event “attributes:inspect[asset]”.

 editor.on('attributes:inspect[asset]', function (item) {
      console.log("asset is added");
      var item_name = item[0].get('name');
      var re = /(?:\.([^.]+))?$/;
      var ext = re.exec(item_name)[1]; 
      console.log(ext);
      ext == "act" && (Sprloader.prototype.createParseButton());
    });
2 Likes