[SOLVED] Finding a random object in an array and modifying it

Hello, I am attempting to find an object from my array of objects at random and then modify its material. Currently, I have this:

var SGamemanager = pc.createScript('sGamemanager');

var shuffleObjects;

//initialize code called once per entity
SGamemanager.prototype.initialize = function() {
    shuffleObjects = this.app.root.findByTag("SO");
    var chosenObject = shuffleObjects[Math.floor(Math.random(shuffleObjects.length - 1))];
    console.log("" + chosenObject);
    chosenObject.entity.model.meshInstances[0].material = new pc.Color(1,1,0,1);

I get the error that entity is undefined.
Any help would be appreciated.

Hello @aperez440! I think the error is because chosenObject is already an entity. Try to replace your line with the line below.

chosenObject.model.meshInstances[0].material = new pc.Color(1,1,0,1);

Unfortunately, that didnt change anything

That’s weird. At the least, the error should be different. Just to be sure, did you save the script after the change?

Please, copy/paste the error as it is in the console or give a screenshot of it.

1 Like

This code is assigning a colour object to a material property

Assuming you want to change the diffuse colour:

chosenObject.model.meshInstances[0].material.diffuse = new pc.Color(1,1,0,1);

I have since then figured it out. Yaustar was correct, I was referencing and changing the material as obosed to referencing the object and then updating it. Thank you very much!

Is there a way to mark a correct answer here?

I don’t think that’s necessary because every answer contributes to a solution. Even if an answer does not immediately solve the problem, it does not mean that the answer is incorrect.