Cycle trough array of materials in scene in TypeScript v5.0.0-alpha.60

Hello All,

I am trying to get a list of all materials in the scene, to render buttons for each material.
My idea was to user scene.materials array.
But the problem is:

console.log(this._scene.materials); // returns array of all materials
console.log(this._scene.materials[0]); //is undefined

Also causes that forEach will not loop through the array.
Is there any special way how to access the scene materials?

Weird, scene.materials array always works fine for me: https://playground.babylonjs.com/#4AJ16M#330

You are right, it works with the javascript version.
I forgot to mention that I am using typescript and doing that in typescript version, it behaves the same in playground - https://playground.babylonjs.com/#4AJ16M#333

console.log(scene.materials);
console.log(scene.materials.length);
console.log(scene.materials[0]);

This is an asynchronity issue.

scene.materials is an array that is being populated by the default material once the scene starts rendering. When you log it it will log the actual object. If you add an object right after logging it, the log will update. this is the meaning behind this warning in the console:

So - when you are checking, scene.materials[0] doesn’t exist. A single frame after it does, and is therefore displayed in the console as well. The object was updated. Try stopping to debug right after logging the object and you will see that it is, in fact, empty when you log it.

2 Likes