The error message showing as "Three.js cannot access the property 'material' of an undefined object"

I'm having trouble understanding why I keep getting this error message:

Cannot read property 'material' of undefined" at line " scene.getObjectByName("cube").material.opacity = control.opacity; "

This is my current code:

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(75, window.innerWidth/window.innerHeight, 0.1, 1000);
var renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
document.body.appendChild(renderer.domElement);

var axisHelper = new THREE.AxisHelper(40); 
scene.add(axisHelper);

var cubeGeometry = new THREE.CubeGeometry(5, 5, 5);
var cubeMaterial = new THREE.MeshLambertMaterial({ color: 0x00ff00 });
var cube = new THREE.Mesh(cubeGeometry, cubeMaterial);

cube.position.x = 0;
cube.position.y = 5;
cube.position.z = 0;
cube.castShadow= true;
scene.add(cube);   

var planeGeometry = new THREE.PlaneGeometry(50, 50, 50)
var planeMaterial = new THREE.MeshLambertMaterial({ color: 0Xcccccc });
var plane = new THREE.Mesh(planeGeometry, planeMaterial);
plane.receiveShadow = true;
plane.rotation.x = -0.5*Math.PI;
plane.position.x = 0; 
plane.position.y = 0;
plane.position.z = 0;
scene.add(plane)

var ambientLight = new THREE.AmbientLight(0x0c0c0c);
scene.add(ambientLight);

var spotLight = new THREE.SpotLight(0xffffff);
var lightHelper = new THREE.SpotLightHelper(spotLight);
spotLight.position.set(10, 50, 20);
spotLight.castShadow = true;
spotLight.shadow.mapSize.width = 1024;
spotLight.shadow.mapSize.height = 1024;

//scene.add(lightHelper)
scene.add(spotLight);


camera.position.x = 20;
camera.position.y = 15;
camera.position.z = 20;
camera.lookAt(scene.position)


function addControlGui(controlObject) {
    var gui = new dat.GUI();
    gui.add(controlObject, "rotationSpeed", -0.01, 0.01);
    gui.add(controlObject, "opacity", 0.1, 1);
    gui.addColor(controlObject, "color");
}

var control = new function() {
    this.rotationSpeed = 0.005 ;
    this.opacity = 0.6;
    this.color = cubeMaterial.color.getHex();
}

var render = function () {
    scene.getObjectByName("cube").material.opacity = control.opacity;
    scene.getObjectByName("cube").material.color = new THREE.Color(control.color);
    cube.rotation.x += 0.1;
    cube.rotation.y += 0.1;
    requestAnimationFrame(render);
    renderer.render(scene, camera);
};
addControlGui(control); 
render();

Answer №1

To locate an Object3D using the method .getObjectByName(string), you must assign a specific name to the object. Even though your mesh represents a cube, without a defined name, the scene will not be able to reference it properly. Therefore, ensure that you set the name property of the cube to be "cube":

var cube = new THREE.Mesh( cubeGeometry, cubeMaterial );
...
cube.name = "cube";
...
scene.add( cube ); 

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

Create a PDF document using HTML code stored on a separate component within an Angular 2 application

I am facing an issue with my parentComponent and childComponent setup. Specifically, I have a button called downloadPDF in the parentComponent that is supposed to trigger a PDF download from the HTML code of the childComponent without displaying the childC ...

The addition of a slash between the hashtag and the anchor name by Fullpage.js is causing conflicts with ng-include

My experience with using fullpage.js on a simple site alongside angular directives has been met with an issue. When including a .phtml file, the anchor functionality of fullpage.js stops working as it adds a slash before and after the anchor name. UPDATE ...

Hindering advancement: Bootstrap Form Wizard causing roadblocks

I am currently facing an issue with my form wizard setup. I want to prevent the user from advancing to the next step when the success key in my json is set to false. It seems like the project is utilizing the bootstrap wizard plugin. You can find more in ...

What types of data are best suited for storage in localStorage?

During the development of my social app with Vue.js and Vuex store, I am contemplating on the best practices for storing parameters in the browser's localStorage. Currently, I retain the 'token' in localStorage, but should I also store &apos ...

Instructions for activating the click function for each individual looping image

When creating a blog page, I am using PHP to loop the like button images according to the total count of posts (example: Facebook like button). The issue I am facing is that while the PHP loop is working, when I click on the first post image, only the firs ...

Retrieve keys from objects by specifying partial key strings using Lodash

Can LoDash's _.filter be utilized in a scenario where you want to retrieve values based on the presence of a specific string within the keys? For instance, consider the following data: Mydata{ "banana" : "1" } If I aim to extract values containing " ...

The color palette of GLTF objects in Threebox

When I use threebox to insert a GLTF object into mapbox using the code below, the object appears darker than expected. Is there an option available to change the color theme of the GLTF object? var options = { obj: './models/WMK-CSC-ALL- ...

After deploying a Next.js project on an Ubuntu server, dynamic pages are returning a 404 error

I've been putting in a substantial amount of time on this project. I'm encountering some 404 errors on my dynamic pages, even though they work perfectly fine on localhost. I've tried using revalidate and playing around with fallback: true an ...

Avoid special characters (metacharacters and diacritical marks)

When my program consumes data from an API, it receives the following output: "<a href=\"http:\/\/www.website2.com\/\" target=\"_blank\">Item card<\/a>","<img src=\"https:\/\/website.com ...

Enhance the JavaScript Array and reformat it once more

Alright, so here's the scenario: var inventory = ["axe", "shield", "bow", "staff"]; I decided to convert this array into a string and store it in my localStorage. localStorage.setItem("inventory", JSON.stringify(inventory)); Then I implemented a f ...

What's the best way to animate the navigation on top of an image for movement?

I am currently in the process of creating my website as a graphic designer. My unique touch is having the navigation positioned on top of an image (which is animated via flash). This setup is featured prominently on my homepage, which is designed with mini ...

Incorporate the "series:" tag into Highcharts directly from the JSON data retrieved from the server

I am facing an issue with creating a Highcharts chart. I am unable to populate the "series" field with the JSON response returned from the server using PHP. The chart is not being rendered and shows a white background instead. Below, you can find the PHP c ...

Saving data from rowclicked event in ag-grid with Angular

My goal is to save the event data from the onRowClicked event in a Component member. This way, when the user clicks a button, the data can be deleted. However, I am facing an issue where the member variable becomes undefined when trying to access it in t ...

Error encountered with Protractor: 'TypeError: undefined is not a function'

I have explored various discussions on this particular error code. Nevertheless, I am finding it challenging to come across any solutions that are effective (or perhaps I am just not understanding them). While constructing a Protractor test for a webpage, ...

Why does one of the two similar javascript functions work while the other one fails to execute?

As a new Javascript learner, I am struggling to make some basic code work. I managed to successfully test a snippet that changes text color from blue to red to ensure that Javascript is functioning on the page. However, my second code attempt aims to togg ...

Is there an issue with MVC5 in passing JSON data to Controller using Ajax?

I am working on implementing duplication checking in my MVC5/EF Code-First application. In the Asset View's Create() method, I use JavaScript to show/hide textboxes for adding a new location_dept/location_room: <div class="form-group"> ...

Is there a way to include a React component within the setContent method of Leaflet?

Is there a way to trigger a React JS component in setContent? I am looking for a solution to add a button within a popup Leaflet, which when clicked will call a React component. While I am aware of the "reactDomserver.rendertostring" method to co ...

The correct method for creating an external JSON file

As I browse through numerous JSON tutorials online, including those on STO, I find myself in a state of confusion when it comes to determining the right approach for writing an external JSON file. I have come across various examples such as: (although Ad ...

Sending data from jQuery to an AngularJS function is a common task that can be accomplished in

In my Controller, I have a function that saves the ID of an SVG path into an array when a specific part of the image.svg is clicked. $(document).ready(function(){ var arrayCuerpo=[]; $('.SaveBody').on("click", function() { ...

Using ng-pattern to validate that a text field does not conclude with a particular term

In this code snippet, I am attempting to prevent a textfield from ending with any of the specified letters in the $scope.pointPattern variable. $scope.pointPattern = /^(?!.*ess|ence|sports|riding?$)/; $scope.error = "not valid"; Upon executio ...