How Can We Help?

This post refers to the new-and-improved beta version of Tabletop Playground, and may describe functionality or UX not present in the legacy version. For information about the beta, click here.
You’ve gotten the hang of creating and editing UI Templates, but now you want to make them do things. Time to get scripting!
This article assumes you already know the basics of Tabletop Playground scripting. If you don’t, you’ll want to read at least Scripting 101 first.
Using refWidget
Let’s start by making a button template. Make sure to name the button something in the hierarchy:

Now let’s write a script to make it do something. As usual, you’ll want to start by bringing in the Tabletop Playground API, only this time, you can use “refWidget.” This is just like refObject for 3D objects – it refers to the UI the script is attached to.

Now we need to get a reference to our button. For this we can use “refWidget.getWidgetByName,” using whatever we named the button we made in the editor.

Then we can add an onClicked listener to make the button do something when we press it; in this case, print a message to the log.

Save the file, then in the UI Template editor, go to the Scripting tab, and attach it.

Save the button. To test it out, we’ll need to add the button to an object or globally (see User Interface Basics for how to do this). Here I’ve added it as Global Screen UI:

Using refObject
If you’re making a UI that you intend to attach to an object, you can use both refWidget and refObject (or any variation thereof).
For example, if we attach this script to a button, and then attach that button to a dice, clicking the button will roll the dice.

Further Reading
If you’d like to see examples of scripts in action, you can copy templates from the Tools package, and look at the scripts attached to them.
We’ve also included examples of some common functions you may want to employ for each widget in their individual Knowledge Base articles, and you can find much more in the UI Element and Widgets sections of the API.
