How to reference GameObject by ID

I feel like this should be a simple answer but I am new here and struggling…

How do I reference the gameobject metrus (created with the Metrus class) to do things with it after it has been created? I need to reference each object individually to do things with it specifically using its ID.

My GameScene:

var metrus = [];

class Metrus extends Phaser.Physics.Arcade.Image {

constructor(scene, x, y, motion, direction, distance, id) {
    super(scene, x, y, 'metrustotalsprite', direction.offset);

	this.id = id;
	this.name = id;
    this.startX = x;
    this.startY = y;
    this.distance = distance;
	this.scene = scene;
	
	this.setDataEnabled();
	this.data.set('id', id);
	
	var unitSprite = this.scene.matter.add.gameObject(this, { shape: 'circle', width: 30, height: 30, circleRadius: 15}).setName(id);	

	unitSprite.displayWidth = 30;
	unitSprite.displayHeight = 30;
	unitSprite.scale = 0.4;

    }

}

class GameScene extends Phaser.Scene {

constructor() {
	super('GameScene')	
}

preload () {
//ASSET PRELOAD HERE, ETC
}

create () {
 //I CREATE MY WORLD TILES HERE AND OTHER SIMPLE FUNCTIONS
//THEN I GO THROUGH AN AJAX CALL TO GET DATA FOR THIS:
thisUnit = metruss.push(this.add.existing(new Metrus(this, centerX + txOffset, centerY + tyOffset, unitAction, unitDirection, 150, unitId)));
									
									
 }

}

So if I have an array of objects called metruss, why does this work:

console.log('UNIT OBJECT ID EXAMPLE:'+metruss[0].name);

And returns the ID of the object I have given it with setName(id)

But this doesnt:

metruss[killunitindex].name.destroy();

This is in a for loop, if that matters, the error I return in browser is:

metruss[killunitindex].name.destroy is not a function

(I appologize if I havent provided enough context for this, I am not trying to overwhelm readability with code)

metruss[killunitindex].name does not refer to your Image. It just refers to an index.
You need to use that index to refer to your Image.

So instead of just pushing into an array, use a key/value dictionary.

    Units = {};
    Units[unitId] = this.add.existing(new Metrus(this, centerX + txOffset, centerY + tyOffset, unitAction, unitDirection, 150, unitId);
1 Like

Ok excellent, I have modified the code to add my units in this way and that appears to work, now how do I reference it to say, destroy it?

If you know the unitId, just do Units[unitId].destroy().