Next.js: GameObject.findObjectsOfType() behaving differently in production

Hi! We’re trying to get Needle to work in a Next.js project, but GameObject.findObjectsOfType(MyScript) is not working the way I expect. We have two script files – let’s say MyScript.ts and MyOtherScript.ts. When I call the method above in react it returns a single instance in dev and in when I build it, it returns two.

This leaves all function calls that I have set up to fail in production. Anyone encoutered this before?

Original Post on Discord

by user 752591281083121724

Hello there – we have an experimental AI bot :robot: that might be able to help you with your question. Would you like to try this out?

Hi, do you perhaps have two instances of MyScript in your scene somehow in production?

Thanks for getting back to me. The two objects are from two different classes. I can see that when I console log them. But I import MyScript inside MyOtherScript. Maybe this can cause the error?

by user 752591281083121724

So in dev you get only “MyScript” and in prod you get [“MyScript”, “MyOtherScript”] ?

Yes!

by user 752591281083121724

Can you show the code that is calling the method? with some context?

Sure! I’m calling the method from a function in a React context. Any calls on this script class instance fails in production because setVisible is undefined.

MyScript


export class MyScript extends Behaviour {
  setVisible(b: boolean) {
    GameObject.findObjectOfType(MyOtherScript)?.setShowObject(b);
  }
}```

**MyOtherScript**
```export class MyOtherScript extends Behaviour {
  setShowObject(b: boolean){
    if (this.object) {
        this.object.children[1].visible = b;
      }
  }
}```

**React Context**

‘use client’;
import { createContext, useContext, useEffect } from ‘react’;

import { MyScript } from ‘@/scripts/MyScript’;
import ‘@needle-tools/engine’;
import { GameObject } from ‘@needle-tools/engine’;

const isClient = typeof window !== ‘undefined’;

export const Context = createContext<null | ContextAttributes>(null);

export default function NeedleContext({
children,
src: srcProp,
…props
}: NeedleContextProps) {

useEffect(() => {
async function importCodeGen() {
try {
const codegen = await import(‘…/generated/gen’);
if (srcProp === undefined) {
setSrc(codegen.needle_exported_files);
}
} catch (e) {
console.error(e);
}
}

importCodeGen();

}, [srcProp]);

if (!isClient) return null;

const setVisible = (show: boolean) => {
try {
const script = GameObject.findObjectOfType(MyScript);
script?.setVisible(show);
} catch (error) {
console.error({ error });
}
};

…```

In this example it seems unneccesary to have two script files, but i just simplified it to make it a little clearer.

by user 752591281083121724

Thanks that makes sense - do you think you could send a bugreport with this little example? That would be great to figure out what’s going on here