How access and call scripts with needle engine WebComponent?

Hello, I’m embedding a Needle Engine project using the <needle-engine> WebComponent.
I would like to access and call scripts (e.g. methods or behaviors) that are part of the original Unity project after it’s loaded on the page.

How can I interact with those scripts or trigger functions from the outside (JavaScript in the host page)?

Is there a way to reference specific behaviours or listen for events exposed by the components?

You can access Needle Engine types globally from window.Needle
Or you can import the scripts like in this example:

import {
  onStart,
  onUpdate,
  Gizmos,
} from 'https://cdn.jsdelivr.net/npm/@needle-tools/engine/dist/needle-engine.min.js';

onStart((ctx) => {
  ...
});

how to call function in custom class ?

import { Behaviour, serializable } from "@needle-tools/engine";

export class CustomScript extends Behaviour {

   callThis()
   {
        console.log("Hello");
   }
}

Could you provide more context? From where do you want to call this function and when?

You can query the component in onStart(ctx => { } and then call it (or when a HTML button is clicked…)

import { onStart } from "@needle-tools/engine"
import { CustomScript } from "<path>"

onStart((ctx) => {
  const comp = ctx.getComponentInChildren(CustomScript);
  if(comp) comp.callThis();
});

// instead of onStart you can do the same when e.g. an HTML button is clicked

I have a deployed project that contains a needle file. How can I import or call that script from another separate project?

import { CustomScript } from “”

Hi oot4chi,

To import or call a Needle Engine script from another separate project, you can use the following approach:

  1. Ensure both projects are set up properly: Make sure your target project has the necessary dependencies installed, including the Needle Engine.

  2. Relative Path Import: When importing the CustomScript, use the correct relative path to the script file. The import statement will look like this:

    import { CustomScript } from "../path/to/your/CustomScript";
    

    Adjust the path accordingly based on where the CustomScript is located in relation to the file you are working on.

  3. Check Exports: Ensure that the CustomScript is correctly exported in the script file where it’s defined. It should be declared as:

    export class CustomScript {
        // Your code here...
    }
    
  4. Verify Module Resolution: If you encounter issues with module resolution, check your project’s configuration (like tsconfig.json for TypeScript) to ensure it includes paths for module resolution correctly.

  5. Usage: Once imported, you can use CustomScript in your code:

    const myScript = new CustomScript();
    

If you have specific errors while importing, please provide details, and I can help further!

1 replies left - Become PRO for more replies.
thread_7EGjzBNumBJf6WPKh7Q1xDkT
Reply to this post directly if you need further help (bottom right button)