Insert Custom JavaScript at Runtime
This guide will show you how to inject JavaScript code at runtime into your creatives. As Unity Playworks Plugin uses Bridge.NET, you can easily call custom JavaScript functions from other libraries directly from your C# project through the Bridge API. The most common use case for this is to add additional HTML/JavaScript elements to enable network trackers.
Custom Javascript Code in LunaPlaygroundField
You can use Bridge.Script.Write()
to insert custom JS at runtime.
Let's create a new C# script, and attach it to a GameObject in the scene.
Initialise a public string and set it to be a JS function in string type, for example:
public string codeMain = "console.log(\"Test\")";
Create an
Awake
function where we'll call the Bridge API methodWrite
, and wrap it in a preprocessor directive (#if UNITY_LUNA
) like in the following example:[ LunaPlaygroundField( "My Code", 0, "Additional Code" ) ]
public string codeMain = "console.log(\"Test\")";
private void Awake()
{
#if UNITY_LUNA
Bridge.Script.Write( "let fn = Function(this.codeMain);" );
Bridge.Script.Write( "fn();" );
#endif
}As you can see, the argument in the
Write
method is currently a string. This will then get converted and executed as JS code in the Unity Playworks Plugin build.Create a Develop Build with the Dev Environment activated.
The
codeMain
variable is set as aLunaPlaygroundField
and it will appear in the Dev Enviroment and Unity Playworks as the following:
In this field, you can now write custom Javascript.
In this example, the custom code in the field is called when the playable starts (**`Test`** should get printed in the browser's console).
Call external JS via Bridge API
If you include External JavaScript libraries into your project, you can use Bridge.Script.Write()
to execute their code. For example, if we add this simple JS script:
function printNumber(n) {
console.log(n);
}
as an external JavaScript library:
You can then call the external library methods by using Bridge API:
public string codeMain = "printNumber(5)"
private void Awake() {
#if UNITY_LUNA
Bridge.Script.Write( "let fn = Function(this.codeMain);" );
Bridge.Script.Write( "fn();" );
#endif
}