Your First Script
This is the sixth tutorial in the Building Your First Lens series. This tutorial series walks through all of the steps for creating your first AR project (Lens) in Lens Studio. At the end of this series you will have recreated the Birthday Countdown sample project, learning all of the steps and pieces to create your own AR experiences.
This step of the tutorial will cover writing your own script using JavaScript to countdown to a specific day. Don't worry if you don't know JS, we will provide the code and walk through all of the steps.
Prerequisites
- Download the latest version of Lens Studio
Writing Your First Script
Right now our Lens is still relatively static, since every time you open it, it has the same message. Adding dynamic content gives the user a reason to come back to your AR experience and writing custom scripts is a great way to achieve this.
Lenses can use JavaScript or TypeScript to add Code into the Lens.
Let's start by adding a new JavaScript asset to our Lens by selecting the + button in the Asset Browser and selecting JavaScript.
We will use this script to countdown to a specific date, so let's name it Countdown Script.
To keep the project clean, we can also create a Script folder and place the new script there.
Now we have our script available for use in your Lens, but we still need to add it to the Scene.
Drag and drop the asset into the Hierarchy to create a Scene Object with this JS file as a component attached to it.
Next, in the Asset Browser, double click the script asset to open up the Script Editor panel where we will write our code.
For TypeScript support or larger Lens projects, we recommend using an external code editor such as Visual Studio Code
Coding can be a scary thing, but it doesn't have to be.
So as we start to code, if you have any questions, you can leverage our AI Chat assistant available in the GenAI Suite.
It is an AI model, trained on all of our documentation and can give you information on AR Concepts, explain a code snippet, or even write code for you given a prompt!
The GenAI Suite can be opened via the button in the upper right corner of the editor.
If you recall from previous sections, the ability to adjust parameters in the Inspector view is extremely powerful.
Let's start by doing just that:
//
tells the editor that this is a comment. Anything on the same line as a //
will not run in your JS code.
The @input
keyword is used by Lens Studio to expose those variables to the Inspector view in the editor
After //@input
, the next value is the type of object we want to allow for assignment in the editor and after that is the name of the variable.
Line 1: Accepts a Text Component which we will use to reference the Happy Birthday Text Component.
Line 2: Takes a string which is any sequence of characters, in our case it will be the text we want to assign.
Let's save the script, by selecting the Script Editor and using the save shortcut, on Mac this is Cmd+S
or Ctrl+S
on Windows.
Then select the script scene object in the hierarchy.
We can now see that our script has two fields we can fill out, just as we defined in the script.
Let`s select the text component field and assign it to subtitle text.
Let's also set the string value we want to assign to this text for testing, the text won't update just yet but we will do this next.
In order to change the value of the text component, we need to first understand how to access the variables we have just set:
Any variable that is set from the inspector using the //@input
keyword can be accessed by using the script keyword.
Other variables defined in the script such as the one on line 4, can be accessed directly by its name without the script keyword.
Example usage of referencing these variables is shown in the print statements on lines 6 & 7.
print()
is a function built into Lens Studio which will output information to the Logger panel to help with debugging.
When we first created the Text Component, we needed to use the Inspector view of the Text Component to access and change the Text property to "Another Year".
Instead, let's do this using code:
On line 9, we are accessing the Text component we have assigned in the Inspector with script.textComponentToChange
. Then we use .text
to access the text property of that component.
With the text field referenced, we can set its value to be equal to the value of the newText
variable.
Save the script, and the text will update in the preview window!
Tip: Text Component properties for scripting can be found here
Now, that we can set the text, let's add a function to calculate the remaining days until the event.
Return to the AI Chat and try and ask the AI assistant to help.
We will copy and paste the generated solution into a new script and add it to the Scene.
Note: Due to the generative nature of the AI Chat, some solutions may be more accurate than others. We will move forward with the solution provided in this video and explain it in more detail in the next step!
Let's take a look at the generated code:
calculateRemainingDays
is a function, which means it can be called at any time, and when called, it will execute the code within it. Line 11 demonstrates how to call the function and Line 8 shows the value that will be returned from executing the function.
It uses the JS Date API to get the time in milliseconds for the current date (line 4) and the target date, (line 5)
Lines 6 & 7 are calculating the difference in ms and then converting from ms to days.
The numbers on line 7 represent the conversion: There are 1000 miliseconds in a second, 60 seconds in a minute, 60 minutes in an hour, and 24 hours in a day. By multiplying those together, we now have our time in number of days.
Let's adjust the code for our use case
The only major change we need to make is to allow this function to be called from our CountdownScript.
We have a couple of options to achieve this, the easiest solution in our case is to change the Scope, (where the function is accessible from), to the global level.
Line 1 now declares a variable that is globally accessible, and the variable stores our function.
Note: Lens Studio provides several global methods that can be used in different scripts, including the print()
function!
Modify CountdownScript.js to use our newly created function:
We have removed a few lines that were no longer needed, and made a couple of changes to our script:
Line 2 is now the targetDate
variable which holds the date we are counting down to. Since it is a //@input
parameter, it can be set in the inspector.
Line 4 shows how we can use our new global function from this script, we are passing in the target date as the parameter so that the function will know which date to calculate the remaining days for.
From here you can save your script and you may notice an error in the logger. Let's fix that in the next step.
As with the TweenManager in a previous section, scripts are executed from top to bottom in the Hierarchy.
If we look closer at the error in the logger, it tells us that CountdownScript.js
on line 4, is trying to call something as a function that is not a function.
This is because CalculateRemainingDays
hasn't set the global variable yet.
Drag the CalculateRemainingDays Object to the top of the hierarchy to ensure it is executed before our script, reset the Lens in the Preview panel, and you will see it working correctly
Now our Lens is working as expected, let's add a couple of lines to add a bit more polish to our Lens
Lines 8 - 10 adjust the text to be singular "Day" when there is only one day remaining until the target date. Otherwise, it will continue to use the "Days left" message from line 6.
This example utlizes an if statement
, more information on conditional statements can be found in these Javascript docs
Lines 11 - 13 check if today is the target date, or if the intended date has already passed.
If that condition is true, line 12 will be executed.
Line 12 turns off the Text component. This is the equivalent of unchecking the checkbox of the Text Component in the Inspector
Summary
Congratulations! Now you have written your first two scripts!
Scripts can work together to adjust the experience of your Lens and give the user a reason to keep coming back.
Utilize the AI Chat feature of the GenAI Suite and the Lens Studio API pages to see how to access properties of different components!