Delete entity script added to root, no response

I want to delete an entity from the screen on the click of the delete button present in the 2D screen on the app. I have added the following script in the ‘root’ of the app. Can someone help me why this is not working and how to make it work?

var DeleteEntity = pc.createScript('deleteEntity');
DeleteEntity.prototype.initialize = function() {
    this.delete_button_entity ="Delete_entity");

    this.delete_button_entity.element.on("click", this.onDeleteButtonClick, this);
DeleteEntity.prototype.onDeleteButtonClick = function(){

        this.entity.destroy(; = null;
DeleteEntity.prototype.update = function(dt) {};

the Delete_Entity contains the button as well as the image to the delete button, here is a link to the project : PlayCanvas | HTML5 Game Engine

Hi @prxnv and welcome,

For start, I think your script isn’t running at all, it seems the Script component in your Root entity is disabled. Try enabling it and check again:


1 Like

Thanks, that was careless of me, I just enabled the script component and I’m getting an error that the delete_button_entity is not defined

I’m thinking most likely that’s coming because entities are being created/added to the hierarchy from top to bottom. So at the moment your script runs the entity you are looking for doesn’t exist yet.

You can solve that in two ways:

  1. Replace initialize with postInitialize in line 4.

  2. Instead of running your script on Root, add an entity at the bottom of your scene hierarchy and add your script to it.

Thanks I tried both the methods but it still returns that the element is not defined : (

So button is not a component of element, but on entity, update your code like this:

this.delete_button_entity = this.entity;
this.delete_button_entity.button.on("click", this.onDeleteButtonClick, this);
1 Like

Thanks, I’m accessing the button directly now, but how do I make the destroy() to work from here?

Which entity are you trying to delete?

Usually you just call destroy on that entity:


In the picker_raycast script, when the user clicks on a entity I do a raycast and store that entity in a window object:

if(typeof window !='undefined'){
    window.__pickedEntity = {};
//after raycast store it as: = result.entity;

I want to delete the entity from the scene once the contains an entity, ie the user clicks on an entity from the scene and then clicks on the delete button.

Ah got it, then it’s as simple as this:

    if(window.__pickedEntity?.active){; = null;