Scripting / VoltCS
Your first script
A button that turns a light on and off for everyone.
The template#
ParelVR SDK > Volt > Create Volt Script gives you this:
using ParelVR.Volt;
using UnityEngine;
public class MyScript : VoltBehaviour
{
public override void OnStart()
{
VoltDebug.Log("Hello from MyScript");
}
public override void OnInteract()
{
}
}
OnStart runs once when the behaviour starts. OnInteract runs when a player clicks the object, so the object needs a collider.
A light switch#
Make a cube with a collider for the button, and a light somewhere in the scene. Put this script on the cube:
using ParelVR.Volt;
using ParelVR.Volt.Objects;
using UnityEngine;
public class LightSwitch : VoltBehaviour
{
public VoltGameObject lamp; // drag the light's object here in the inspector
[VoltSynced] private bool isOn = true;
public override void OnInteract()
{
TakeOwnership(); // only the owner can change synced fields
isOn = !isOn;
RequestSerialization(); // send the new value to everyone
Apply();
}
public override void OnDeserialization()
{
Apply(); // a new value arrived from the owner
}
private void Apply()
{
lamp.SetActive(isOn);
}
}
Press Play and click the cube. Then try it with two players in Multi-Client Play Mode: each player sees the light change, and players who join later get the current state.
Inspector fields#
Public fields, and private fields marked [VoltSerialize], show in the inspector and are saved with the scene, like in Unity.
Events you will use first#
| Event | When |
|---|---|
OnStart |
Once, before the first OnUpdate. |
OnUpdate |
Every frame. |
OnInteract |
A player clicked the object. |
OnPickup, OnDrop |
A player picked up or dropped the object (needs a VoltPickup). |
OnPickupUseDown, OnPickupUseUp |
The trigger was pressed while holding it. |
OnPlayerJoined, OnPlayerLeft |
Someone joined or left the instance. |
OnPlayerEnterTrigger, OnPlayerExitTrigger |
A player walked into or out of a trigger collider. |
All of them are in Events.
Calling methods by name#
SendCustomEvent("Name") calls a public method (or one marked [VoltEvent]) on the same behaviour. UI buttons and animation events call methods the same way. SendCustomEventDelayedSeconds and SendCustomEventDelayedFrames call one later.
Coroutines work too: StartCoroutine with an IEnumerator, yielding VoltWait instructions.
