Build in the world

Unity addons

Scripted worlds, props, avatar features and client packages. This page covers the networking, player and content APIs, and the rules for which code is allowed to run.

The SDK ships a full creator guide with worked examples and the sandbox reference. Open it from Basis > Creator Guide in the Unity editor, or read it at docs.basisvr.org. This page is the condensed reference. Where they differ, the version that ships with the SDK you're building against wins.

Two ways to ship code

Sandboxed scripts (Cilbox)

Mark a script [Cilboxable] and it travels inside your world, prop or avatar file. The client runs it in an interpreter, and it can only call APIs on an allowlist, mostly the Basis.Shims classes. Use this for anything you upload and share.

Native packages

An ordinary Unity package compiled into a client build. It has full access to the framework: menus, settings, input and new components. Use this for client features and for components you want added to the content allowlist.

The component allowlist

When the client loads a world, prop or avatar, it destroys every component whose type isn't on that content type's allowlist. The lists are the ContentPoliceSelector assets in com.basis.sdk/Settings/. They match on the exact Type.FullName, so a subclass of an allowed type isn't allowed automatically. Content can't add types at runtime. In practice:

  • Uploaded content can use the built-in components (BasisSyncedTransform, BasisPickupSyncNetworking, BasisSeatSync and others) plus its own Cilbox scripts.
  • A new native component only works in content once it's on the allowlist in the client build players actually run. If you'd like one added to GoodMorningVR, tell us and send the source.
  • Check before you build: Basis > Tools > Cilbox Permissions shows what the sandbox allows.

Package layout

A native addon is a standard UPM package. List the Basis packages you depend on under vpmDependencies, which the Basis Package Manager reads, and reference the assemblies you use in your .asmdef.

{
  "name": "com.example.morningbell",
  "displayName": "Morning Bell",
  "version": "0.1.0",
  "description": "A networked bell for event hosts.",
  "author": { "name": "Example Studio", "url": "https://example.com" },
  "license": "MIT",
  "vpmDependencies": {
    "com.basis.common": "1.0.0",
    "com.basis.framework": "1.0.0",
    "com.basis.sdk": "1.0.0"
  }
}

Common assembly references: Basis Framework (with a space), BasisSDK, BasisNetworkCore, BasisCommon, BasisSettings, BasisEventDriver, and Cilbox plus BasisShims for sandboxed code. There's no addon manifest or discovery step: packages hook in with components and [RuntimeInitializeOnLoadMethod] registrars. Good packages to read: com.basis.vehicles (native networking), com.basis.pooltable (a large Cilbox game) and com.basis.examples.

Networked behaviours

Derive native world and prop scripts from Basis.BasisNetworkBehaviour. Each instance gets a network id and an owner, and it can send byte messages to the other copies of itself on other players' clients.

using Basis;
using Basis.Network.Core;
using Basis.Scripts.Networking.NetworkedAvatar;

public class MorningBell : BasisNetworkBehaviour
{
    private byte rings;

    public void Ring()
    {
        if (!HasNetworkID) return;
        rings++;
        SendCustomNetworkEvent(new byte[] { rings }, DeliveryMethod.ReliableOrdered);
        PlayBell();
    }

    public override void OnNetworkMessage(ushort playerId, byte[] buffer, DeliveryMethod delivery)
    {
        if (buffer == null || buffer.Length != 1) return;
        rings = buffer[0];
        PlayBell();
    }

    public override void OnPlayerJoined(BasisNetworkPlayer player)
    {
        if (IsLocalOwner())
        {
            SendCustomNetworkEvent(new byte[] { rings }, DeliveryMethod.ReliableOrdered, new ushort[] { player.playerId });
        }
    }

    private void PlayBell() { /* ... */ }
}

Members

MemberMeaning
HasNetworkID, NetworkIDSet once the server has resolved this object. You can't send before then.
SendCustomNetworkEvent(byte[] buffer, DeliveryMethod method = Unreliable, ushort[] recipients = null)Relayed by the server. null recipients means everyone except you. Include your own id to receive it yourself.
SendCustomNetworkEventDirect(…, bool allowServerFallback = true)Sends over peer-to-peer links when they exist. Received in OnDirectNetworkMessage.
TakeOwnership(), TakeOwnershipAsync(int timeout = 5000)Become the owner, even if someone else owns it. The async version returns BasisOwnershipResult { Success, PlayerId }.
RequestWhoIsOwnershipAsync(), CurrentOwnerIdAsk the server who the owner is, or read the cached value.
IsLocalOwner()True when the server has confirmed that you own it. IsOwnedLocallyOnClient turns true as soon as you ask.
OnNetworkReady()The id is resolved and messages can flow.
OnOwnershipTransfer(BasisNetworkPlayer newOwner)The owner changed. It can fire twice if the new owner hadn't finished joining yet.
OnServerOwnershipDestroyed()Nobody owns it any more.
OnNetworkMessage(ushort playerId, byte[] buffer, DeliveryMethod method)A message arrived. playerId is the sender.
OnPlayerJoined, OnPlayerLeftSomeone joined or left the instance.
SendCustomEventDelayedSeconds(Action, float), …DelayedFramesLocal timers that run on Update, LateUpdate or FixedUpdate.

Rules that catch people out

  • Call the base. If you override Start or OnDestroy, call base.Start()/base.OnDestroy(). If you declare a new non-override Start, the object never joins the network.
  • Hierarchy is identity. A scene object without a server-assigned id takes its id from its hierarchy path, sibling index and component type. Every client needs the same hierarchy, and renaming or moving an object changes its id.
  • No replay for late joiners. Messages aren't stored. The owner has to send current state from OnPlayerJoined, as in the example above.
  • Size. Unreliable and sequenced messages must fit in one packet: about 988 bytes minus framing (4 bytes, 2 more per listed recipient, plus encryption overhead). Larger sends with those methods throw. ReliableOrdered and ReliableUnordered can fragment.
  • Encrypted by default. Messages are end-to-end encrypted between clients. Reliable sends made before keys are set up are queued (up to 256, for 10 seconds). Unreliable ones are dropped.
  • Validate input. Any player in the instance can send your object bytes. Check lengths and ranges, and check that the sender is allowed to do what the message asks.

DeliveryMethod

ValueBehaviourUse for
Unreliable (4)May drop or arrive out of orderHigh-rate continuous state
Sequenced (1)May drop, never out of orderLatest-value streams
ReliableSequenced (3)Only the newest packet is guaranteed; can't fragmentLatest state that must eventually land
ReliableOrdered (2)Guaranteed, in order, can fragmentEvents, game moves, full-state syncs
ReliableUnordered (0)Guaranteed, any order, can fragmentIndependent chunks

Synced objects and variables

For state that changes continuously, derive from Basis.Scripts.Networking.Sync.BasisSyncedObject instead of sending bytes yourself. It handles send rate, keyframes, interpolation, extrapolation, distance-based reduction and peer-to-peer. BasisSyncedTransform, BasisSyncedRigidbody and BasisPickupSyncNetworking are ready-made subclasses.

public class SpinningSign : BasisSyncedObject
{
    private BasisSyncHandle angle;

    private void Awake()
    {
        angle = RegisterAngle(interpolate: true);   // register in Awake, same fields and order on every client
    }

    protected override void OnBeforeTransmit()      // owner: runs only when a send is due
    {
        LocalSet(angle, transform.localEulerAngles.y);
    }

    protected override void ApplyInterpolated()     // everyone else
    {
        transform.localRotation = Quaternion.Euler(0f, GetAngle(angle), 0f);
    }
}
  • Register… covers Position, Rotation, Scale, Float, Int, UShort, UInt, Byte, Bool, Angle, Vector2, Vector4 and Color. Pass a BasisQuantSpec (Half, or Ranged(min, max, bits)) to send fewer bytes.
  • BindTransform(target, position, rotation, scale) wires handles straight to a transform. ForceKeyframe() sends a full update now.
  • Inspector settings include SendIntervalSeconds (default 0.05), KeyframeIntervalSeconds (0.5), UseDirectP2P, RelevanceRadius and TeleportThreshold.
  • A custom subclass is a new component type, so the allowlist applies to it in uploaded content.

Players

APIMeaning
BasisNetworkPlayer.LocalPlayerYou.
BasisNetworkPlayer.GetAllPlayers(), GetPlayerCount(), GetPlayerById(ushort, out player)Everyone in the instance.
BasisNetworkPlayers.TryGetPlayerByUUID(string, out player)Look up by identity (the did:key).
player.playerId, player.displayName, player.IsLocal, player.GetPosition()Per player. playerId is per session. IBasisPlayer.UUID is the lasting identity.
OnPlayerJoined, OnPlayerLeft, OnLocalPlayerJoined, OnRemotePlayerJoined (static events)Join and leave notifications.
BasisLocalPlayer.Instance.Teleport(position, rotation, bypassStand = false, mode = WorldRoot)Move the local player. Modes are WorldRoot, WorldFeet, FacePoint and ToPlayer. A seated player stands up first unless bypassStand is set.
BasisLocalPlayer.Instance.Respawn(), Immobilize(bool)Send back to spawn, or freeze movement.
SetWalkSpeedOverride(key, v), SetJumpHeightOverride, SetGravityOverride, ClearLocomotionOverride(key)Keyed overrides, so several scripts can adjust movement without overwriting each other.
BasisLocalPlayer.OnLocalAvatarChanged, IBasisPlayer.OnAvatarSwitched, BasisAvatar.OnAvatarReadyAvatar loaded or changed.

Bone, tracking and VR-state getters work only on the local player. Sandboxed scripts use BasisPlayersShim instead (All, Local, GetByUUID, Nearest, Within), and BasisNetworkShim for messages, with events instead of overrides.

Avatar features

Avatar-side networking derives from BasisNetworkAvatarBehaviour. Override OnNetworkReady(bool isLocallyOwned) and OnNetworkMessageReceived(ushort remoteUser, byte[] buffer, DeliveryMethod method), and send with NetworkMessageSend(buffer, method, recipients). An avatar can have at most 256 of these, indexed by their order in the hierarchy. Avatar content has the strictest sandbox and allowlist.

Interactables and pickups

Subclass BasisInteractableObject for custom hover and interact logic. Implement CanHover, IsHoveredBy, CanInteract and IsInteractingWith, and override OnInteractStart/OnInteractEnd. Or use BasisPickupInteractable (OnPickupUse, Drop(), grip, snapping and auto-return settings) and network it with BasisPickupSyncNetworking. BasisSeat covers sitting. Sandboxed scripts use BasisInteractableShim.

Worlds, props and avatars

  • World: one BasisScene per scene, with SpawnPoint, RespawnHeight (default -100) and MainCamera.
  • Prop: a BasisProp on the prefab root.
  • Avatar: a BasisAvatar with its Animator, eye and mouth positions, and viseme and blink meshes.
  • Each has a BasisBundleDescription (name, description, icon, tags, author, contact, licence, credits). Fill it in honestly, because players see it.

Build from the component's inspector, or with Basis > Build > Bulk Build. The output is one password-encrypted .bee file holding a bundle per platform. Host it on any static host that supports HTTP range requests, then share the URL and password. Web players also need CORS headers on that host. Content you share on GoodMorningVR follows the Community Guidelines.

To load content for everyone at runtime, from a native script:

BasisNetworkSpawnItem.RequestSceneLoad(password, beeUrl, persist: false, admin: false,
    out LocalLoadResource scene, loadStrategy: 2);

BasisNetworkSpawnItem.RequestGameObjectLoad(password, beeUrl, position, rotation, Vector3.one,
    false, false, false, out LocalLoadResource prop);

Load strategy 0 is immediate, 2 waits until every client has the file (or 5 minutes pass), and 3 only pre-downloads. Unload with RequestGameObjectUnLoad(netId) or RequestSceneUnLoad. Hooks for build tooling: BasisBundleBuild.PreBuildBundleEvents and BasisAssetBundlePipeline.OnBeforeBuildPrefab.

Add a main-menu button from a native package:

using Basis.BasisUI;
using UnityEngine;

public class MorningBellMenu : BasisMenuActionProvider<BasisMainMenu>
{
    [RuntimeInitializeOnLoadMethod]
    public static void AddToMenu() => BasisMenuBase<BasisMainMenu>.AddProvider(new MorningBellMenu());

    public override string Title => "Morning Bell";
    public override string IconAddress => "...";
    public override int Order => 80;
    public override bool Hidden => false;
    public override void RunAction() { /* open your panel */ }
}

Store settings with a typed binding. Register the class so values load after the settings file is read:

public static class MorningBellSettings
{
    static MorningBellSettings() { BasisSettingsBindingPostLoad.Register(typeof(MorningBellSettings)); }

    public static BasisSettingsBinding<bool> Enabled =
        new("morningbell.enabled", new BasisPlatformDefault<bool>(true));
}

Enabled.RawValue reads it, Enabled.SetValue(x) writes it, and OnChanged fires on change. For a section in the Settings menu, see SettingsProvider.AddContentTab and DeveloperSectionBuilders. The recorder package (com.basis.developer.recorder) is a short working example. Sandboxed content can add up to four settings tabs and one panel through BasisMenuShim.

Frame hooks

  • BasisEventDriver.OnUpdate and OnLateUpdate are static events on the client's single frame loop.
  • BasisFrameSyncRegistry.Register(IBasisFrameSync) runs your FrameSync() in the window where reading and writing transforms is safe.
  • BasisLocalPlayer.JustBeforeNetworkApply.AddAction(order, fn) and its siblings run work at fixed points in the local player's update.

Sandbox limits

Cilbox scripts run in an interpreter with a time budget per call (500 ms by default, 1 s at most). The main limits:

  • No LateUpdate, coroutines, AddComponent, SendMessage or BroadcastMessage.
  • Scripts can't derive from BasisNetworkBehaviour; use BasisNetworkShim.
  • The shim doesn't forward peer-to-peer messages.
  • Maths-heavy code runs far slower than native, so keep hot loops small.
  • BasisScriptBus passes messages locally between pieces of content.