Writing scripts
An interpreted script is an ordinary Unity MonoBehaviour in Assets/VirtuademyEnvironmentScripts. You attach it to a GameObject in a scene or in a prefab, set its fields in the Inspector, and it runs when the world opens, like any other component.
- Any namespace works, or none.
- Unity messages (
Awake,Start,Update,OnTriggerEnter, …) work as usual. - For anything that takes time, use coroutines (
StartCoroutine(IEnumerator)):Taskandasync/awaitare not allowed. - To reach the platform — the player, the session, the language — use the scripting API below.
The scripting API
The API has two entry points. The split tells you who answers a call: the app the user is running, or the platform behind it.
IVirtuademyGameplay.Current (namespace Virtuademy.Environments.ScriptingApi) — the app and the world:
| Group | What it does |
|---|---|
Player | The avatar's transforms (Root, Head, LeftHand, RightHand), Teleport, EnableMovement, avatar visibility, and the camera: first or third person, static / drag-rotation / free camera, speed, MoveCameraTo, PanCameraAround, ExitCameraPan (see The camera) |
Scene | InitializePlaceholders, spawned-object visibility, RunTransition, ReturnToLobby, SpawnProjectAsset, SpawnContainer, the Ready and Unloading events, RunWhenReady, RunBeforeUnload |
Tools | Tool-inventory opacity, answer feedback, hiding the contextual menu, adding a pickable to the inventory |
Interaction | The SelectedChanged event, which reports a change of selection, not every click: see Reacting to every click |
Localization | Current and previous language, AvailableLanguages, Translate(key), SetLanguage, LanguageChanged, IsAvailable (see Texts in more languages) |
Screen | FadeToBlack, FadeFromBlack |
Help | Opening and closing the help panel, when the app has one |
Platform | IsVR, IsWebGL, IsMobile |
IVirtuademyFramework.Current (namespace Virtuademy.ScriptingApi) — the platform:
| Group | What it does |
|---|---|
Session | Session id, multiplayer and master client, network time, the environment, the shard, the local user, GetUser, FindExperience, JoinExperience, the OtherPlayerEntered / OtherPlayerLeft events |
SaveData | Get, Set and Delete the local player's saved values, SubmitLeaderboardRecord |
Analytics | Send analytics events, generate an experience id: see Analytics from a script |
Methods that take time return an IEnumerator: run them in a coroutine (yield return …) and, where offered, pass a callback to receive the result.
Current exists only inside a Virtuademy app. In the Editor, in Play mode of your own project, it throws an exception: check IVirtuademyGameplay.IsAvailable or IVirtuademyFramework.IsAvailable first if the code can run there.
Example
A door that fades the view, moves the player to a destination and fades back in:
using System.Collections;
using UnityEngine;
using Virtuademy.Environments.ScriptingApi;
public class FadeTeleportDoor : MonoBehaviour
{
[SerializeField] private Transform destination;
// Hook this to an Interactable, a button or a trigger.
public void Enter()
{
if (!IVirtuademyGameplay.IsAvailable)
{
return;
}
StartCoroutine(EnterRoutine());
}
private IEnumerator EnterRoutine()
{
IVirtuademyGameplay world = IVirtuademyGameplay.Current;
yield return world.Screen.FadeToBlack();
yield return world.Player.Teleport(destination);
yield return world.Screen.FadeFromBlack();
}
}
A sign that greets the user by name, with TextMeshPro:
using TMPro;
using UnityEngine;
using Virtuademy.ScriptingApi;
public class WelcomeSign : MonoBehaviour
{
[SerializeField] private TMP_Text label;
private void Start()
{
if (IVirtuademyFramework.IsAvailable)
{
label.text = "Welcome, " + IVirtuademyFramework.Current.Session.LocalUserName;
}
}
}
Reacting to every click on an Interactable
The scripting API has no event for a click. IVirtuademyGameplay.Current.Interaction.SelectedChanged reports a change of selection: a click on an Interactable selects it and raises the event, and the next click on the same object deselects it instead of selecting it again, so the event does not fire on every click.
To run a method of your script on every click, go through a Visual Scripting graph:
- On the Interactable, give the Visual Scripting Interactable Placeholder a script machine and enable its Interacting state. Leave Selected off if every click must count: with both states, the first click selects the object and only the second one interacts (see Interactable).
- In the graph, connect the On Interact event to the Send Message node of
GameObject, targeting the GameObject that carries your script, with the name of a public method of your script as the message. - Write the method in your script.
using UnityEngine;
public class ClickCounter : MonoBehaviour
{
private int clicks;
// Called by the graph: On Interact -> GameObject: Send Message.
public void OnObjectClicked()
{
clicks++;
Debug.Log("Clicks: " + clicks);
}
}
SendMessage is refused in a script (see Security rules), but not in a graph: the graph is not a script. This path was tried in the WebGL player with a mouse: the method ran on every click, repeated clicks included.
A click on your own screen-space UI can also raise On Interact on the object you last pointed at. See Your own on-screen UI.
Your own on-screen UI
The platform does not pass a click to the world when the pointer is over its own interface. For a Unity UI canvas, the check is on the layer: a click is taken as made on the interface when the last UI hit is a GameObject on the UI layer (layer 5). A canvas created from code sits on the Default layer, and a click on its buttons then also reaches the Interactable behind it: it raises On Interact on the object you last hovered. This was seen in the WebGL player with a mouse.
- Put your own screen-space canvas and all its children on the UI layer. A canvas you create in the Editor with the UI menu is on that layer already, and so are its children; a canvas and the objects you add to it from code are not.
- A script can also filter the click itself, with
EventSystem.current.IsPointerOverGameObject(); for a touch, pass the finger id.
using UnityEngine;
using UnityEngine.EventSystems;
public class ClickCounter : MonoBehaviour
{
// Called by the graph: On Interact -> GameObject: Send Message.
public void OnObjectClicked()
{
if (PointerIsOverUi())
{
return;
}
// The click was meant for this object.
}
private static bool PointerIsOverUi()
{
EventSystem eventSystem = EventSystem.current;
if (eventSystem == null)
{
return false;
}
if (Input.touchCount > 0)
{
return eventSystem.IsPointerOverGameObject(Input.GetTouch(0).fingerId);
}
return eventSystem.IsPointerOverGameObject();
}
}
Unity reads the state of the previous frame in IsPointerOverGameObject, which is enough inside a click handler like this one.
Your own raycast and the application's pop-ups
A raycast you cast yourself on a click (Camera.main and Physics.Raycast) also gets the clicks made on the application's own pop-ups, such as the buttons of the welcome pop-up: the object behind the pop-up is hit as if the user had clicked it. EventSystem.current.IsPointerOverGameObject() does not report the pointer as over these pop-ups, so the check above does not filter them.
Do not use your own raycast for the clicks on the objects of the scene. Make those objects Interactables and use the path described above, On Interact and Send Message: the platform does not pass to an Interactable the clicks that land on its own interface.
Analytics from a script
The payloads of IVirtuademyFramework.Current.Analytics.Send(verb, payload) are the classes of Virtuademy.ScriptingApi (ExperienceStartDTO, ExperienceStepStartDTO, ExperienceStepCompleteDTO, ExperienceCompleteDTO…). Their key, the field that ties an event to a run, is protected, and the Visual Scripting nodes fill it for you. A script can create a payload but cannot set its key from outside, so declare a subclass of each payload you send and set the fields in its constructor:
using Virtuademy.ScriptingApi;
public class StartPayload : ExperienceStartDTO
{
public StartPayload(string experienceKey, string startContext)
{
key = experienceKey;
context = startContext;
Verb = EAnalyticVerb.ExpStart;
}
}
public class StepCompletePayload : ExperienceStepCompleteDTO
{
public StepCompletePayload(string experienceKey, string step, int points, int maxPoints, int passingPoints,
EExperienceOutcome result, EExperienceScoringType scoring)
{
key = experienceKey;
stepId = step;
score = points;
maxScore = maxPoints;
passingScore = passingPoints;
outcome = result;
scoringType = scoring;
Verb = EAnalyticVerb.StepComplete;
}
}
public class CompletePayload : ExperienceCompleteDTO
{
public CompletePayload(string experienceKey, int points, int maxPoints, int passingPoints,
EExperienceOutcome result, EExperienceScoringType scoring)
{
key = experienceKey;
score = points;
maxScore = maxPoints;
passingScore = passingPoints;
outcome = result;
scoringType = scoring;
Verb = EAnalyticVerb.ExpComplete;
}
}
Then ask the platform for the experience id, wait for it, and send the events in the order of the Analytics nodes: start, steps, complete.
using System.Collections;
using UnityEngine;
using Virtuademy.ScriptingApi;
public class TrainingAnalytics : MonoBehaviour
{
private const string Key = "Training01"; // 15 characters at most
private void Start()
{
if (IVirtuademyFramework.IsAvailable)
{
StartCoroutine(Run());
}
}
private IEnumerator Run()
{
IAnalyticsApi analytics = IVirtuademyFramework.Current.Analytics;
// Nothing can be sent for this key until the id is ready: wait for onReady.
bool ready = false;
StartCoroutine(analytics.GenerateExperienceGuid(Key, () => ready = true));
while (!ready)
{
yield return null;
}
analytics.Send(EAnalyticVerb.ExpStart, new StartPayload(Key, "Forklift training"));
// ... the learner works through the steps ...
analytics.Send(EAnalyticVerb.StepComplete,
new StepCompletePayload(Key, "step-1", 1, 1, 1, EExperienceOutcome.Pass, EExperienceScoringType.Numeric));
analytics.Send(EAnalyticVerb.ExpComplete,
new CompletePayload(Key, 7, 10, 6, EExperienceOutcome.Pass, EExperienceScoringType.Numeric));
}
}
The key may contain only the characters 0-9, A-Z, a-z, ? and !. With any other character, an underscore or a dash for example, the request for the id never completes: onReady is never called, nothing is sent, and the log shows no error. This is a known limit of the platform today.
An event sent with a key whose id has not been generated is refused with an exception. A run sent this way appears in Analytics ▸ Experiences of the Back Office, listed by the context of its start event: see Experience Analytics.
A call that fails never returns
When a call of the scripting API fails, nothing tells you. Its callback never runs, a coroutine that waits for it (yield return …) never resumes, a Visual Scripting node that awaits it never continues, and the log shows no error. This was seen with the analytics key (see the limit above). The other calls that take time are built the same way, according to the code, but only the analytics case was tried.
A step of your environment that waits for such a call can therefore wait forever, with the user stuck in it. Give every wait a timeout and a fallback, such as continuing without the result or asking again with another value:
using System.Collections;
using UnityEngine;
using Virtuademy.ScriptingApi;
public class SafeExperienceId : MonoBehaviour
{
// Asks for the experience id and gives up after timeoutSeconds.
// done receives true when the id is ready, false when the wait timed out.
private IEnumerator GenerateId(string key, float timeoutSeconds, System.Action<bool> done)
{
bool ready = false;
StartCoroutine(IVirtuademyFramework.Current.Analytics.GenerateExperienceGuid(key, () => ready = true));
float deadline = Time.realtimeSinceStartup + timeoutSeconds;
while (!ready && Time.realtimeSinceStartup < deadline)
{
yield return null;
}
done(ready);
}
}
The while (!ready) loop of the analytics example above has no way out: add a limit like this one before you rely on it.
The camera
- The platform camera is
Camera.main, the Character Camera. Use it to raycast or to read where the user is looking, and keep your own cameras out of the scene (see Scene setup). - The legacy
Inputclass works in the app, also when your Unity project is set to use only the new Input System. In the Editor's Play mode of such a project it throws, so guard calls that only run in the app. PanCameraAround(target, maxZoom, minZoom, maxYRotation, minYRotation, maxXRotation, minXRotation, cameraInteraction)(the Free Camera Pan node, which passescameraInteraction: true) puts the camera on an orbit aroundtarget, at 5 m × zoom: it starts atmaxZoom(0.12 is 0.6 m) and the zoom takes it out tominZoom. The Y limits are the elevation, the X limits the horizontal angle, in degrees and intarget's own frame (0 and 0: behind it, level with it), so keeptargetlevel and turn it to choose the starting side. WithcameraInteraction, the user turns the camera around by dragging with the right mouse button (one finger on mobile); callUseFreeCamera()first, as the 2026.6 tests did. The camera starts at 0 on both axes whatever the limits, and jumps into the elevation range at the first drag: include 0 in it. Details: Free Camera Pan.PanCameraAround(target)(the Character: Pan node) is the same with the default zoom,0.0001, which puts the camera practically ontarget:targetis then the viewpoint, a Transform you place in front of the object, looking at it. In one 2026.6 test the camera ended about 1.5 to 2 m from a viewpoint 0.6 m from the object: when the distance matters, passmaxZoom, or useMoveCameraTo(target)to a Transform you place (and rotate yourself, if the view must turn around the object).
Members that can be missing in the app
The app is built with code stripping, which removes the members of the .NET libraries that the app does not use. Your scripts are compiled apart from it, so a call can compile, pass the security check and still throw MissingMethodException in the app. This happens, for example, with System.Text.StringBuilder: Append(char) and Append(int) throw in the WebGL player. Build text with string concatenation instead:
// Throws MissingMethodException in the app:
// var builder = new System.Text.StringBuilder();
// builder.Append('#').Append(score);
string label = "#" + score;
Other members the app never calls can be missing in the same way: when a call fails like this, replace it with a plainer one (concatenation, an array or a List<T>) and test it in a world.
Objects you create at run time
The platform sets up the placeholders of the scene when the world loads. An object you create yourself afterwards, with Instantiate on a prefab that carries placeholders, is not set up: call InitializePlaceholders on the new instance, and pass true as the second argument when the placeholders are on its children too.
GameObject copy = Instantiate(prefab, position, rotation);
IVirtuademyGameplay.Current.Scene.InitializePlaceholders(copy, true);
The same is available in a graph as the Initialize Placeholder node.
Texts in more languages
The texts of an environment come from its Localization File (see The Localization File). A script reaches them through IVirtuademyGameplay.Current.Localization:
Translate(key)returns the text of the key in the current language, or the key itself when the file has no row for it. The result is a fixed text: it does not change when the user switches language.LanguageChangedis raised after a language change. Its argument is the name of the previous language: readCurrentLanguagefor the new one. Translate again there every text your script shows.SetLanguage(name)takes the name of the language (for exampleItalian), not its code.AvailableLanguageslists every language the application knows, which can be more than your organization offers.IsAvailableis false where the application has no localization, for example in a world opened from the editor:Translatethen returns the key.
A text that only needs to follow the language needs no script: use a Localization Placeholder, and change its key with the Set Key node.
A counter that keeps its label in the user's language:
using TMPro;
using UnityEngine;
using Virtuademy.Environments.ScriptingApi;
public class StepCounter : MonoBehaviour
{
[SerializeField] private TMP_Text label;
private int step = 1;
private void Start()
{
if (!IVirtuademyGameplay.IsAvailable)
{
return;
}
IVirtuademyGameplay.Current.Localization.LanguageChanged += OnLanguageChanged;
Refresh();
}
private void OnDestroy()
{
if (IVirtuademyGameplay.IsAvailable)
{
IVirtuademyGameplay.Current.Localization.LanguageChanged -= OnLanguageChanged;
}
}
public void NextStep()
{
step++;
Refresh();
}
private void OnLanguageChanged(string previousLanguage) => Refresh();
private void Refresh()
{
label.text = IVirtuademyGameplay.Current.Localization.Translate("steps/counter") + " " + step;
}
}
What differs by platform
Player.Head,LeftHandandRightHandare not null on WebGL. They already exist at the first ready step (RunWhenReady, or theReadyevent): they belong to the avatar, which stays hidden there. They do not tell you that a headset or tracked hands are present: usePlatform.IsVR,IsWebGLandIsMobilefor that.- Environments with C# scripts load on the Android and iOS apps only on a platform at version 2026.6.1 or later. On an earlier platform the app cannot load the scripts and the world does not open: ask your administrator which version the tenant runs before you test on a phone. WebGL and VR do not have this limit.
Good practices
- Keep scripts small and focused on the environment. Behaviour that the SDK already provides as a placeholder or a prefab works better as such.
- Run a build early: the security check points at the exact file and line of anything it refuses.
- Test in a world on every platform the scene targets. In the Editor the API is not available, so the parts that use it are only exercised in the app.