0

Im pretty new, hope someone can help with this trivial question :) The array is globaly defined var textMeshes = []; and a function to generate the text at a certain position The function works but i cannot access the array by index, I get a console error that textMeshes is not defined. But if i log textMeshes console.log(textMeshes) as hole array i see the array is filled. console.log(textMeshes[0]) results in undefined. I guess the issue is because fontLoader loads asyncron but please correct me if im wrong =). I really appreciate your help!

function addTextToScene (posX, posY, posZ, i){

                var fontLoader = new THREE.FontLoader();
                fontLoader.load( 'fonts/droid/droid_sans_regular.typeface.json', function ( font ) {

                    var textGeometry = new THREE.TextGeometry( '#' + i, {
                        font: font,
                        size: 16,
                        height: 5,
                        curveSegments: 12,
                        bevelEnabled: true,
                        bevelThickness: 1,
                        bevelSize: 0,
                        bevelSegments: 5
                    } );


                 textMesh = new THREE.Mesh( textGeometry, textMaterial );

                 var textMaterial = new THREE.MeshPhongMaterial({ color: 0xff0000, specular: 0xffffff, shininess: 100, emissive: 0xffffff});

                 textMesh.position.x = posX;
                 textMesh.position.y = posY+50;
                 textMesh.position.z = posZ-50;

                 textMeshes.push( textMesh );
                 scene.add( textMesh );


                } );




            }

1 Answers1

0

You are correct: the FontLoader.load() callback is asynchronous, so textMeshes going to be empty until after its content is loaded. Only then will this line take place:

textMeshes.push( textMesh );

before that, textMeshes[0] is going to be undefined because texMeshes has nothing inside it; it has a length of 0.

This is not much of a Three.js question, but more of an AJAX question. You should read this discussion to get more acquainted with the topic: How do I return the response from an asynchronous call?

M -
  • 26,908
  • 11
  • 49
  • 81
  • Thanks for the link i will read it asap, but this seems a good hint. –  Nov 09 '18 at 20:55