2

I'm using React and ThreeJS to import a 3D model into a web page. The problem is in the function to load the mesh into my ThreeJS scene. I'm getting the following error:

TypeError: Cannot read property 'scene' of undefined

Right befor the line I add the mesh into the scene I print out the same object and there is a property 'scene' inside my GLB file. Here is an image:

enter image description here

Here is my code:

import React, { Component } from 'react'
import * as THREE from 'three'
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader';
import gltfPath from '/home/mateus/Documents/index/src/cube.glb'


class ThreeDViewer extends Component {
    componentDidMount() {
        const width = this.mount.clientWidth
        const height = this.mount.clientHeight

        this.scene = new THREE.Scene()

        this.camera = new THREE.PerspectiveCamera(75, width / height, 0.1, 5000)
        this.camera.position.z = 20

        this.renderer = new THREE.WebGLRenderer()
        this.renderer.setSize(width, height)
        this.mount.appendChild(this.renderer.domElement)

        const geometry = new THREE.BoxGeometry(1, 1, 1)
        const material = new THREE.MeshBasicMaterial({ color: '#00ff00' })

        this.cube = new THREE.Mesh(geometry, material)

        this.light = new THREE.AmbientLight(0xffffff, 100)
        this.scene.add(this.light)

        this.loader = new GLTFLoader()
        this.loader.load(gltfPath, function (gltf) {
            // I print gltf but I can't add it to my scene I don't know why
            console.log(gltf)
            this.scene.add(gltf.scene.children[2])

        }, undefined, function (error) {
            console.error(error)
        })


        this.start()
    }

If I add the cube from the ThreeJs lib it works fine, but with my custom model it doesn't work. THe model is just a simple cube exported as glb by blender 2.81.

1 Answer 1

2

this is undefined in your callback, try using an arrow function instead of a function declaration:

this.loader.load(gltfPath, (gltf) => {
  this.scene.add(gltf.scene.children[2]);
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.