An error occurred in scene.js at line 68: TypeError - Unable to access properties of an undefined object (specifically 'scene')

I'm attempting to display a animated model(.glb) in three.js but I am encountering the error mentioned above. When I place the LoadAnimatedModel function within the main method, it functions correctly. However, if I utilize it in a separate class, it no longer works. The LoadStaticModel function works fine, but the animated function does not. Any insights into what may be causing this issue? Thank you in advance!

Below is the provided code snippet:

class CharacterControllerInput{
   mixers = [];
   scene;
  constructor(scene){
    this.scene = scene;
    this.LoadAnimatedModel();
  }

   LoadAnimatedModel(scene){
    this.scene = scene;

    const loader = new GLTFLoader();
    loader.load( 'http://127.0.0.1:3000/docs/BeterWerktDit.glb', function ( gltf ) {

      gltf.scene.traverse( function ( object ) {

        if ( object.isMesh ) object.castShadow = true;

      } );


      const model1 =  SkeletonUtils.clone( gltf.scene );


      const mixer1 = new THREE.AnimationMixer( model1 );


      mixer1.clipAction( gltf.animations[ 0 ] ).play(); 

      
      this.scene.add( model1);
      this.mixers.push( mixer1);

      render();

    } );
  }

Here is an abbreviated version of the class where I instantiate the Class.

class Scene{

  constructor(){
    this.main();
  }
    main(){

    const canvas = document.querySelector('#c');


    const renderer =  new THREE.WebGLRenderer({canvas, antialias: true});


    const scene = new THREE.Scene();
    




      this.character = new CharacterControllerInput(scene);
    render();

       function render(){

        const width = window.innerWidth;
        const height = window.innerHeight;
        camera.aspect = window.innerWidth/window.innerHeight;
        camera.updateProjectionMatrix();
  
        renderer.setSize(width, height, false);
  
        const delta = clock.getDelta();
        for (const mixer of mixers) mixer.update(delta);

        renderer.render(scene, camera);
        requestAnimationFrame(render)
      }
      requestAnimationFrame(render);
  }
  
};

let _APP = null;

window.addEventListener('DOMContentLoaded', () => {
  _APP = new Scene();
});

Answer №1

The issue has been successfully resolved by identifying that the callback function was incorrectly using this.scene, causing a reference problem.

Below is the corrected code:

class CharacterControllerInput {
	scene;
	constructor(scene, mixers) {
		this.scene = scene;
		this.mixers = mixers;
		this.LoadAnimatedModel();
	}

	_init() {
		this.LoadAnimatedModel();
	}

	LoadAnimatedModel() {
		const loader = new GLTFLoader();
		const scene = this.scene;
		const mixers = this.mixers;

		loader.load('http://127.0.0.1:3000/docs/BeterWerktDit.glb', function (gltf) {

			gltf.scene.traverse(function (object) {

				if (object.isMesh) object.castShadow = true;

			});

			const model = SkeletonUtils.clone(gltf.scene);

			const mixer = new THREE.AnimationMixer(model);

			mixer.clipAction(gltf.animations[0]).play();

			scene.add(model);
			mixers.push(mixer);

		});
	}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Customizing error messages in Joi validationorHow to show custom

Hi there, currently I am utilizing "@hapi/joi": "^15.1.1". Unfortunately, at this moment I am unable to upgrade to the most recent Joi version. This represents my validation schema const schema = { name: Joi.string() .all ...

Working with JavaScript's push() method for JSON data manipulation

How can I populate a JSON variable with data in the following format? [ "name":"sample name" ,"first_name":"sample first" ,"last_name":"sample last" ,"email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b6c5d7dbc6dad398f6d ...

"Utilizing Javascript filtering to narrow down results based on date ranges within a Vue

I'm currently using Vue within a Laravel application. Most of the functionality is working as expected, except for the last part. I've been struggling to come up with the right search terms for this scenario. Apologies if this question has alread ...

JAVASCRIPT ENCOUNTERS ISSUE WITH RANDOM TEXT GENERATION

Utilizing an array of words, we are in the process of generating random text. The goal is to shuffle and combine these words to form new "random sentences". However, we have encountered a minor issue - the addition of "undefined" at the beginning of each p ...

Having a problem with the glitch effect in Javascript - the text is oversized. Any tips on how to resize

I found some interesting code on the internet that creates a glitch text effect. However, when I implement it, the text appears too large for my webpage. I'm struggling to adjust the size. Here is the current display of the text: too big This is how ...

The interactions and functionalities of jQuery sortable and draggable elements

Looking for some assistance with a project involving draggable objects 'field' and 'container', along with a sortable object 'ui-main'. The goal is to drag the two aforementioned objects into 'ui-main', while also al ...

Leveraging the $dirty property in AngularJS to determine if any changes have been made to a form

Recently, I've been attempting to determine if my form is being edited by monitoring certain fields. I've come across $dirty as a potential solution for this task, but unfortunately, I'm struggling to identify what exactly I'm overlooki ...

Is it possible to create a pitch shifter with the web-audio-api?

Creating a Pitch Shifter with Node.js Hello, I am new to web development! I am currently working on developing an online audio player that requires a pitch shifter. I have been attempting to grasp the concept of the web audio API, but find it challengin ...

What is the best way to activate a click event on a dynamically generated input element with the type of 'file'?

I am facing a challenge in dynamically adding an input field of type 'file' to a form. The requirement is to allow the end user to add multiple files to the form, necessitating the use of an array concept. While I am able to inject dynamic elemen ...

Having trouble with JavaScript not functioning correctly within the Update Panel?

Does anyone know how to include JavaScript from a remote source inside an update panel? I'm trying to add Facebook and Twitter share buttons to my application. Here is the code snippet: The problem is that this code works fine when the page is initia ...

Displaying a div when a button is clicked (PHP)

Hello everyone, I'm new to posting here so please bear with me if I seem inexperienced. On my website, there is a button that needs to disappear when clicked and be replaced by a form without refreshing the page. I was able to accomplish this using ...

Ways to determine if a string or HTML contains repeated consecutive elements

Assume I am working with the following string <div id="ch">abcdefg<img /><img />hij</div> <div id="ad">abc<img />defg<img />hij</div> strHtml = $('div#ch').html(); strHtmlFalse = $('div#ad&ap ...

End: unrelated, lacking responses

I have a question I'd like to discuss: Whenever I utilize the following code snippet: async function createNewElement(req,res){ const start1 = new Date().getTime(); console.log("start time 1 ", start1) await new Promise((resolve) => setT ...

Learn how to efficiently transfer a dynamic subtitle text value from an HTML5 video player to a database

I have successfully developed an HTML5 video player with subtitles. Currently, my goal is to allow the user to submit the subtitle text at a specific timestamp to a database. Despite trying various methods, I am facing challenges in fetching the subtitle t ...

Ways to present a Nuxt page as a reply from an express route

How can I achieve a similar functionality to res.render on a Nuxt page? The project is using the nuxt-express template, which combines Nuxt and Expressjs. Although Nuxt provides nuxt.render(req, res) and nuxt.renderRoute, I am having trouble making it wo ...

Mongoose Alert Utility Directive

const mongoose = require('mongoose'); module.exports = { init: () => { const dbOptions = { useNewUrlParser: true, useUnifiedTopology: true, autoIndex: false, reconnectTries: Number.MA ...

Unable to insert an array within a function

I've searched for the answer but couldn't find it - my array is not pushing to datahasil. How can I push the array hasil into datahasil...?? const data1 = await JadwalBooking.aggregate([{ $project: { "keterangan": "$keterangan", ...

Utilizing React Material UI for form validation with error handling and informative helper text

I recently created a form in which I needed to validate the inputs. During my research, I came across the material UI library that has an attribute called error boolean, and another attribute called helperText for the TextField input of the form. However ...

Can you conceal a JavaScript function within a specific scope?

Suppose I have two functions a and b that I want to keep within a certain functional scope. Since they share some common code, I decide to extract this shared functionality into another method named support. support should be accessible by both a and b, b ...

Modify the td attributes while retaining the extracted data values from the website

I'm currently utilizing this code to extract data from another website: $searchURL = "http://www.anotherwebsite.com"; $html = file_get_contents($searchURL); $patternform = '/(<tbody.*<\/tbody>)/sm'; preg_match_all($patternfor ...