Sansar Docs
  • 🚀Welcome to Sansar
  • 📚GLOSSARY
  • 🎏Patch Notes
  • 😇Work in Progress
  • ⚠️Creative Commons License
  • Support
    • General Troubleshooting
      • General FAQ
      • The Sansar Cache
      • The Sansar Log
    • Contact Support
  • Sansar Basics
    • Installation And Compatibility
      • Installing Sansar
      • System Requirements
      • Sansar Compatibility FAQ
      • Sansar on Mac
      • Body Tracking Vive
      • Configuring Firewalls
    • Account Management
      • Account Set Up
      • Avatar Name and ID
      • Adding Payment Method
      • Discord FAQ
      • Steam Integration
      • Subscription FAQ
    • Controls
      • Avatar Hand Gestures in VR
      • FreeCam and CineCam
      • Game Controller Buttons
      • HTC VIVE controls
      • Keyboard Shortcuts for Editing a Scene
      • Keyboard Shortcuts for Styling Your Avatar
      • Keyboard Shortcuts for Visiting an Experience
      • Mouselook Mode
      • Oculus Rift Controls
      • Vive Index Controls
    • Settings
      • General Settings
    • VR Settings
      • VR Settings Menu
      • Calibrating Height in VR
  • Exploring in Sansar
    • Navigate and Explore
      • The Codex
      • Instances
      • Interactive objects
      • The Main Menu
      • The Nexus
      • Portals
      • Quests
      • Quick Start: Exploring in Sansar
    • Socialize And Connect
      • Chat Panel
      • Experience Points, Levels, and Titles.
      • Finding People in Sansar
      • Identifying Interacting With Avatars
      • The People panel
      • User profiles
    • Attending events
      • Deploying Unpublished Event to Event World
      • Adding Events to Your Calendar
      • Attending Events in Sansar
      • Avatar Broadcasting FAQ
      • Creating Your Own Events
      • Redemption Codes
      • Tipping
    • Share Content
      • Streaming Sansar
      • Taking a photo
  • Avatar Creation
    • Avatar Basics
      • Avatar 2.0 FAQ
      • Customizing Your Avatar
      • Avatar Emotes
      • The Avatar Editor
    • Dressing The Avatar
      • Fitting Designer Clothing to your Avatar
      • Setting Custom Emotes
      • Wearing Accessories
      • Wearing Rigged Clothing
    • Managing Avatar Items
      • Importing Avatar-Related Items
      • Editing an inventory item's name
      • Editing an inventory item's image
      • Deleting avatar looks from your inventory
      • Importing a custom emote animation
      • Managing your avatar looks inventory items
    • Avatar Resources
      • Avatar Reference Files
      • Blender - Avatar files
      • Blender - Using Decimate Tool
      • Exporting Custom Avatars From Blender
      • Sansar Skeleton Skinning Details
      • Using Animation Skeleton
  • Creating In Sansar
    • Importing Things to Sansar
      • Supported file types
      • AABB Bounding Box and Item Restrictions
      • Importing Audio
      • Importing a Custom Avatar
      • Importing World Items
      • Importing Collision Volumes
      • Importing Accessories
      • Importing Clothing
      • Importing Emotes
      • Importing Hair
      • Importing Custom Scripts
      • Importing a Skybox
      • Troubleshooting Import Errors
    • Shaders and Materials
      • Shaders Information
      • Materials Information
      • VAT Shader Guides
        • VAT Shader Basics
        • VAT Technical Info
      • Displacement Guides
        • Simple Displacement
        • Advanced Displacement
    • Marvelous Designer Info
      • Marvelous Designer Integration
      • Marvelous Designer Creator Resources
      • Marvelous Import and Export
      • MD Limitations
    • Shader Scripting
    • Materials editing and shaders
    • Creator Tools
      • Creating a World
      • Creating Quests
      • Diagnostics Toolbar
      • Importing Items to Sansar
      • My Worlds Panel
    • Managing Worlds
      • Quick start: Creating experiences in Sansar
      • Deleting an experience or scene
      • Deploying a new scene to an existing experience
      • Editing a scene
      • Experience memos
      • Linking A Scene To A World
      • Managing your scenes and worlds
      • Moderation Tools for World Owners
      • Publishing Options for Your Experiences
      • Renaming a scene
      • Saving and Building A Scene
      • Sharing Your Experiences
      • Visiting your own experience
    • Part Of The World Editor
      • Object Stats Toolbar
      • Object Components
      • Parenting objects
      • Scene Item Inventory
      • Scene Objects Panel
      • Collision Volumes
      • Scene Settings
      • System objects
      • Object Motion Types
    • Working With Scripts
      • Working With Scripts
      • Working With Trigger Volume
      • Referencing Scene Components
      • Intro to Scripting in Sansar
      • Using the Script Console
      • Setting Script Parameters
      • Adding Scripts to an Object
      • Configuring Teleport Scripts
      • Simple Script User Guide
    • Working With Audio and Video
      • Working With Audio
      • Creating Media surface
      • Streaming Web Audio
      • Audio Emitter
      • Sansar Audio FAQ
      • Using Media Streams
      • Ambisonic Sounds
      • High Quality Spacial Audio
      • Audio Resource - Room Tones
      • Previewing Audio and Video in a Scene
      • Using Audio Materials
    • Working With Lights
      • Working With Lights
      • Light Types
      • Global Illumination
  • Sansar Store
    • Using the Sansar Store
      • The Sansar Store
      • Buying Items From The Store
      • Redelivering Lost Purchases
    • Buying and Selling Sansar Dollars
      • Gifting Sansar Dollars
      • Buying Sansar Dollars
      • Converting Sansar Dollars
      • Processing US Dollar Credit
    • Selling Your Content
      • Hidden Store Listings
      • Selling Items in Sansar Store
      • Selling Items in an Experience
      • Allowing Resale Of Items
      • Buyers Permissions
  • Guidelines and Moderation
    • Guidelines and Policies
      • Terms of service
      • Sansar's Discord Server Rules
      • Community Standards
      • Content Guidelines
      • World Publishing Guidelines
      • Store Listing Guidelines
      • Store Banner Guidelines
      • Event Guidelines
      • Privacy Policy
      • Sansar Freeware License Agreement
      • Intellectual Property Infringement Notification
      • Cookie Policy
    • Moderation and Reporting
      • Abuse and Griefing
      • Blocking Avatars
      • Muting Avatars
      • Reporting abuse
      • Reporting issues and bugs
      • Security issues
  • Script API Docs
    • General Information
      • External Script Repository's
      • Sansar Script API
      • Script API Updates
      • Restricted API's
    • Example Scripts
      • Example Scripts in Sansar
      • Cannonball
      • Follow The Path
      • Random Movement
      • Reflective Detector
      • Simple Script
      • Sound Randomizer
      • Stats Example
      • Teleport Hotkeys
      • Visitor Tracker
      • Mover Examples
    • Sansar Namespace
      • Namespace
      • Color
      • Mathf
      • Quarterion
      • Vector
      • Vector Extensions
    • Sansar.Script Namespace
      • AddEntryAttribute
      • CancelData
      • ComponentID
      • CoroutineException
      • Default Attributes
      • Editor Visible Attribute
      • Entries Attribute
      • Event Data
      • ICoroutine
      • IEvent Subscription
      • Instance Interface
      • Locked Attribute
      • Log
      • MaxEntriesAttribute
      • Memory
      • MinEntriesAttribute
      • NonReflectiveAttribute
      • ObjectID
      • OperationCompleteEvent
      • RangeAttribute
      • Reflective
      • Script.Base
      • Script Event Data
      • Script Handle
      • ScriptID
      • SessionID
      • Simple Script Event Data
      • ThrottleException
      • Timer
      • Tooltip Attribute
    • MetaData Namespace
      • Assembly MetaData
      • Script MetaData
    • Sansar Script Testing Namespace
      • Assertion Failure Exception
      • Assertions
    • Sansar Utility Namespace
      • GenericEnumerable <T>
      • GenericEnumerable<T>.GetItem
      • JSON Serialization Data
      • JSON Serialization Data 1
      • JSON Serializer
      • JSON Serializer Options
    • Sansar Simulation Namespace
      • Agent Info
      • Animation
      • Audio Component
      • Camera Control Mode
      • Character Tracker
      • Chat
      • Client
      • Cluster
      • Command Action and Data
      • Component Type
      • Control Point Type
      • Held Object
      • HTTP
      • Interaction
      • Light
      • Media Action
      • Mesh Component
      • Modal Dialogue
      • Move Mode and Mover
      • Objective
      • PlayHandle
      • PlaySettings
      • PlayStatus
      • Quest
      • RayCastHit
      • Rigid Body
      • Scene
      • Scene Public
      • Simple Script
      • Sit Event Type
      • Sit Object Data
      • Sound Resource
      • Stream Channel
      • Tutorial Hint
      • UI
      • User Data
Powered by GitBook
On this page
  • Introduction to scripting in Sansar
  • Getting set up
  • Writing your first script
  • Brief tour of the API
  • An object oriented API
  • Events
  • Editable properties
  1. Creating In Sansar
  2. Working With Scripts

Intro to Scripting in Sansar

Overview of Sansar scripting

PreviousReferencing Scene ComponentsNextUsing the Script Console

Last updated 2 months ago

Introduction to scripting in Sansar

Scripts allow us to make interactive and reactive content in Sansar. They are written in C# but are designed to be used and reused without scripting knowledge or even seeing the code. Once uploaded or purchased through the Sansar Store, scripts can be added to objects while editing a scene. They can then be configured through properties specified by the script creator.

The script interface to Sansar is referred to as the Script API. It is constantly evolving as new features are added for interacting with objects, users, and other scripts.

Scripts run on the scene server, where they have access to server authoritative information such as the physics system, the users in the scene, and other scripts. Through the server’s connection to the users it is also possible, with some latency, to do some limited, client-focused interactions.

Getting set up

After you install Sansar, there is a Client\ScriptApi folder inside your Sansar install directory (C:\Program Files\Sansar\ by default). This contains the technical API documentation as well as some example scripts. If you have VisualStudio, you can copy the entire ScriptApi/ directory to a more convenient place and open ScriptApi/Examples/ScriptExamples.csproj. This project is set up to understand the Sansar API and includes all the examples.

You can also find the most recent API documentation online here: .

Writing your first script

The easiest way to get started with a script is to use the base class, like this:

public class MyScript : Sansar.Simulation.SceneObjectScript { }

This script doesn't do anything- but it will compile! You can upload it by following the directions in the article and then . It doesn’t do anything yet, so let’s make it say something. For this case, we are going to write to the script log, once, on initialization.

public class MyScript : Sansar.Simulation.SceneObjectScript { public override void Init() { Log.Write("Hello World!"); } }

Now when we upload this script, then add it to an object and build then visit the scene, we can find this message in the . Lastly, for our very simple starter script we are going to make things a little neater. There are a couple of script interfaces we are almost always going to use, so adding a few ‘using’ lines at the top lets us use them without writing out the full name every time. We're adding more than strictly needed for this example but this will make it easier to extend the example for more complex code.

using System; using Sansar; using Sansar.Script; using Sansar.Simulation;

public class MyScript : Sansar.Simulation.SceneObjectScript { public override void Init() { Log.Write("Hello World!"); } }

Note: Sansar supports C# script files up to 1MB in size.

Brief tour of the API

    • This root namespace has only a few base math types and some related math libraries: Vector and Quaternion.

    • Most interfaces for scripts or the “script system” itself are in the Sansar.Script namespace. This includes things like timers, ID types, memory use, logging and various attributes.

    • These interfaces are for interacting with the simulated world or the users in it. Some things in here are:

      • Object interfaces for creating new objects or physics interactions of objects.

      • User interfaces for information about users in the scene as well as sending them chat or sounds or simple UI dialogs; or teleporting them.

      • Scene interfaces for information about the scene as well as playing sounds scene-wide.

An object oriented API

SimpleScript contains the other API access points for the script; directly itself or inherited from its base class ScriptBase. Those members and some notable APIs are:

    • FindAgent to get AgentPrivate APIs to the visitors of the scene.

    • FindObject to get ObjectPrivate APIs to other objects in the scene.

    • Chat to subscribe to chat messages and send chat messages to users and other scripts.

    • User to subscribe to events when users enter or exit the scene.

    • CreateCluster to add new objects to the scene.

    • Position, Rotatation and related physics simulation information.

Events

A script that says Hello World in the logs isn’t exactly useful or interactive. To make a script interactive, we need it to respond to something happening: an event. An event can be many things, including a collision, someone entering the scene or leaving it, a chat message, a keyboard press, a message from another script, and more.

SimpleScript has some methods you can override to handle common events. It is also possible to set up your own subscription explicitly through a Subscribe method. Here we will be using SimpleScripts overrides, which do all the setup work for us.

Let's update the hello world script to instead greet users as they arrive in the scene. We don't need the SimpleInit any more, so we will replace it with an override of OnAddUser(AgentPrivate agent):

using System; using Sansar; using Sansar.Script; using Sansar.Simulation;

public class MyScript : SimpleScript { protected override void OnAddUser(AgentPrivate agent) { Log.Write("Hello!"); } }

Now whenever a new visitor arrives in the scene, the method OnAddUser runs and writes "Hello!" to the logs.

For our greeter we want to send a chat message to the user that just logged in, welcoming them to our scene. An agent is a server-side representation of a logged in user, and it has a reference to a Client API we can use to sent them a chat message.

using System; using Sansar; using Sansar.Script; using Sansar.Simulation;

public class MyScript : SimpleScript { protected override void OnAddUser(AgentPrivate agent) { // Send the chat message to their client agent.Client.SendChat("Welcome to my scene!"); } }

Once we add this script to an object in the scene, all visitors arriving in the scene are greeted by a message in their chat window welcoming them.

Editable properties

While our greeter is at least a little interactive, it isn’t very easy to customize or reuse. If we want to say a different message, we would need to modify the source code and re-upload the script. Sansar scripts show their public fields in the object properties for any object the script is on. We can use this to show a Message field that lets us change the message without recompiling or re-uploading the script.

using System; using Sansar; using Sansar.Script; using Sansar.Simulation;

public class MyScript : SimpleScript { public string Message;

protected override void OnAddUser(AgentPrivate agent) { // Send the chat message to their client agent.Client.SendChat(Message); } }

Now after adding this script to an object in the scene and opening that object’s properties window, we will see this:

Note the Message attribute and blank text field.

If we put this script on the Sansar Store, anyone could adjust the message as they needed, and we could use the same script in different scenes with different messages without recompiling. We can make it even better with a couple of attributes. Attributes in C# are ways of attaching extra information to pieces of code. In this case we will use the [DisplayName("")] and [DefaultValue("")] attributes to give us a more meaningful name and an example message which will help make it clearer how to use the script. To apply these to our Message field we simply place them above the field.

using System; using Sansar; using Sansar.Script; using Sansar.Simulation;

public class MyScript : SimpleScript { [DisplayName("Greeter Message")] [DefaultValue("Welcome to my scene!")] public string Message;

protected override void OnAddUser(AgentPrivate agent) { // Send the chat message to their client agent.Client.SendChat(Message); } }

Now looking at the properties for an object with this script will show this, which is more user friendly:

Message has become Greeter Message, and the text field is populated with a default message.

SimpleScript event overrides

SimpleScript offers several overrides to handle common event types.

  • OnAddUser(AgentPrivate agent) : When a user joins the scene.

  • OnRemoveUser(AgentInfo agentInfo): When a user leaves the scene.

  • OnTimer(): Automatically called 10 times a second.

  • OnCollision(CollisionData data): Called when the object the script is on collides with another object.

  • OnChat(ChatData data): Called whenever there is chat on channel 0.

  • OnScriptEvent(ScriptId sender, Object data): Called when scripts send script events to this script.

Since the default values on these overrides may not always be the best, SimpleScript also includes some Attributes to adjust them: change the rate of OnTimer, set what types of objects cause OnCollision, which channel to listen to for OnChat and more. It is also possible to use these attributes to create extra event handlers, by applying them to other methods that match the function list of the overrides.

Lastly there are a couple of helper methods and properties in SimpleScript worth pointing out:

Check out for another look at what you can do using .

The full scripting API docs can be found in the Sansar install directory in Client/ScriptApi/index.html, or in the section of this Knowledge Base. This is a brief overview of how the API is laid out:

has a few unit-test related APIs.

contains the GenericEnumerable class used to create enumerables for other APIs.

Sansar’s script API is very object oriented. This means that nearly all APIs are accessed through a specific instance of an interface. A script gets access to those API instances through the base class it extends- in our example, that is . Previously we just casually used Log.Write(“Hello World!”); so let’s take a little bit of a closer look at it. SimpleScript has a member property Log of type . This log returns the instance of the logging API for the scene. The script then calls the Write method specifically on that instance of Sansar.Script.Log. Different scripts could actually get a different instance of Sansar.Script.Log - and when multiple script owners in a scene become possible they will! For now, however, all scripts in a scene are owned by the scene owner and thus all share the same Log.

Three of the largest APIs have multiple instances based on how much access they give; some can do more things than others. Those APIs that end in Public (, , and ) are the least powerful as they are intended to be used “by anyone”. Those that end in Private (, , and ) are more powerful as they offer access to more private internals. Scripts that are on objects built into the scene get access to ScenePrivate while visiting scripts would only get access to ScenePublic.

: Access to the Scene APIs and a way to find many other APIs.

: Access to APIs for the object the script is attached to:

GetComponent: Objects are primarily a collection of parts called components. They may contain one or more of , , and which can be accessed with GetComponent.

: For writing to the script debug console (Ctrl+D).

: For information on how much memory is available to scripts, how much is used, and subscribing to events related to memory use levels.

RigidBodyComponent: This property will be the of the object the script is on.

GetSubscription(string methodName): Gets an for the named method, if it is subscribed to events either as an override or with an attribute. This IEventSubscription can be used to cancel the events.

Sansar Script API
SceneObjectScript
Importing items to Sansar
attach it to an object
script log (Ctrl+D)
Example script: Simple Script
SimpleScript
Script API Documentation
Sansar
Sansar.Script
Sansar.Simulation
Sansar.Testing
Sansar.Utility
SimpleScript
Sansar.Script.Log
ScenePublic
AgentPublic
ObjectPublic
ScenePrivate
AgentPrivate
ObjectPrivate
ScenePrivate
ObjectPrivate
RigidBodyComponent
AnimationComponent
AudioComponent
Log
Memory
RigidBodyComponent
IEventSubscription