How do I access variables on instances of objects?

Apologies for how basic this question is, but I have spent hours at this to no avail.

Here is a very basic script that has a public field for a MeshRender (which is assigned in the inspector in Unity)

`import { Behaviour, MeshRenderer, serializable } from “@needle-tools/engine”
import { Object3D } from “three”;

export class SphereMeshController extends Behaviour
{

@serializable(Object3D)
public sphereMesh?: MeshRenderer;

DisableMesh()
{
    if(this.sphereMesh != null)
    {
        this.sphereMesh.enabled = false;
    }

}

} export default SphereMeshController;`

I am calling DisableMesh() like so from a different script, by creating an instance of the SphereMeshController object.

let sphereController = new SphereMeshController(); sphereController.DisableMesh();

however within the DisableMesh() method, the sphereMesh variable is always null.

Ive read through the documentation and the only thing I can see is that I could maybe try and do this through events, but that seems overly complex for such a trivial action.

Am I doing something unbelievably stupid? Any links to relevant documentation or examples would be appreciated. I looked through the scripting docs on the website but haven’t seen the solution.

Original Post on Discord

by user 259070246382469121

Hi,

I see two things in the script that you can fix and then it will work:

  1. Your script references a MeshRenderer but tells Needle Engine that it is a Object3D - the two types are not the same. Replace @serializable(Object3D) with @serializable(MeshRenderer)

  2. You are creating a new component instance with new SphereMeshController() instead of using the one that you have in your scene (added it in Unity as a componet to a gameobject). Instead ifyou want to use it then you need to either reference it in the other script that is trying to access them (if it’s also a component for example) OR simply calling const sphereController = GameObject.findObjectOfType(SphereController) which will search it in the scene (that’s the equivalent to the Unity findObjectOfType call)

These are the relevant docs pages:

Marcel,
Thank you for the detailed response. Clearly I was being an idiot. That worked perfectly. Thank you for all the work you do here.

by user 259070246382469121

Glad it works now :slightly_smiling_face: no problemo