Call method in index.html

Is there any way to call methods in index.html? like this Unity - Manual: Interaction with browser scripting. There are .jslib files used for connection

Afaik there is no way to do this from generated c# class, because there are only declarations of methods in .ts file.

All I need is call method from index.html when button clicked in Unity

Original Post on Discord

by user 267660755443122181

With “methods in index.html” you mean code that is set up there?
There is no “script boundary” in Needle Engine, one of the main advantages. All is in javascript module scope. So you can call code much more flexible as with jslib

You don’t add code in C#, you add it in TypeScript

yes, call method inside <script></script> tags index.html

by user 267660755443122181

In C#, we declare jslib methods like this:

[DllImport (“__Internal”)]
static extern void Login (string hostUrl);

How to convert this to TypeScript?

by user 267660755443122181

Can you tell a bit more what you want to do? Do help properly that would be helpful

My understanding is:

  • you have a component on an object
  • something happens (e.g. something is clicked) and you want to call a method that is in a module somewhere else entirely (e.g. a js file referenced from index.js or directly in index.js)
  • you also want to wire that up as event in Unity?

Okay, I have a button and I can detect click on that button. I want to call js method inside index.html file when button clicked. Simple console.log is enough for testing

by user 267660755443122181

This is how my .ts file looks
image.png

by user 267660755443122181

@herbst🌵 any tips?

by user 267660755443122181

There’s like a million ways ranging from super dirty to very clean :slightly_smiling_face:

Here’s one way - it’s just JavaScript, there’s no artificial boundaries, as long as your script tag in the index.html comes before the needle engine code your code will be available anywhere.
image.png

Access via global script tag:

Another cleaner way with modules and importing/exporting methods


Importing a module with custom code:

You can also find a sample setup with Unity here if that’s helpful @Nurlan
https://github.com/needle-tools/needle-engine-samples/tree/main/package/Runtime/Javascript-Interop

You can drop this file into Unity for installation: https://engine.needle.tools/downloads/unity/samples