Script fails to calculate meshInstances if model gets unloaded

Hi there, I’m using this

var nearPlacements = [];
var closestDistance = 30;
playerPosition = this.player.getPosition();
  var placements ='Placement');
 placements.forEach( function(placementsEntity){
        var distance = playerPosition.distance(placementsEntity.getPosition());
        if (distance < closestDistance) {

if (nearPlacements.length == 0) {
console.log('No near entities');
//Set checker variable to 'True'
} else {
    var totalTriangles = 0;
        for (var i = 0; i < nearPlacements.length; i++) {
            if (nearPlacements[i].model) {
           var meshInstances = nearPlacements[i].model.model.meshInstances;
var mat;
var matEach = 0;
for (var i2 = 0; i2 < meshInstances.length; i2++) {
    mat = parseFloat(meshInstances[i2].mesh.indexBuffer[0].numIndices / 3);
    matEach += mat;
      totalTriangles += matEach;

To calculate meshInstances of objects near the player, the problem it fails sometimes if models are unloading I think

Uncaught TypeError: Cannot read properties of null (reading ‘meshInstances’)

On this line:
var meshInstances = nearPlacements[i].model.model.meshInstances;

Shouldn’t if (nearPlacements[i].model) { fix the problem?

Hi @Newbie_Coder,

Yes that’s expected, if the model resource is unloaded there are no mesh instances to calculate the bounding box from.

You will have to reload it, or if you loaded it at least once and it’s static / on the same place, to keep a reference somewhere of its bounding box. And rewrite the code above to use that.

In my case the models have to be unloaded and forgotten to the next time I load them again, it works as expected just that
if (nearPlacements[i].model) {
Doesnt prevent it from getting error, it should skip entities with no model comp

In my case
if (nearPlacements3[i5].model.model != null) {
solved the problem :nerd_face: