# SceneObjectScript

Kind: Class · Namespace: Sansar.Simulation · Assembly: Sansar.Simulation.dll · Script API 47.10.0

<div class="api-meta">
<span class="api-kind api-kind-class" data-pagefind-filter="kind:Class">Class</span>
<span data-pagefind-filter="namespace:Sansar.Simulation">Namespace <a href="/scripting/api/sansar.simulation"><code>Sansar.Simulation</code></a></span>
<span>Inherits <a href="/scripting/api/sansar.script/scriptbase">Sansar.Script.ScriptBase</a></span>
</div>

<span id="T:Sansar.Simulation.SceneObjectScript"></span>

Extend SceneObjectScript to create a script that can be used on content that is natively in the scene. This is the primary script type in Sansar.

```csharp
public abstract class SceneObjectScript : Sansar.Script.ScriptBase
```

## Remarks

Override [`ScriptBase.Init`](/scripting/api/sansar.script/scriptbase#init) for script initialization, primarily event subscriptions.



Use [`SceneObjectScript.ObjectPrivate`](/scripting/api/sansar.simulation/sceneobjectscript#objectprivate) to access the Object the script is on.



Use [`SceneObjectScript.ScenePrivate`](/scripting/api/sansar.simulation/sceneobjectscript#sceneprivate) to access the Scene the object is in.



```csharp title="SceneObjectScriptExample.cs"
/* This content is licensed under the terms of the Creative Commons Attribution 4.0 International License.
 * When using this content, you must:
 * •    Acknowledge that the content is from the Sansar Knowledge Base.
 * •    Include our copyright notice: "© 2022 Sansar, Inc."
 * •    Indicate that the content is licensed under the Creative Commons Attribution-Share Alike 4.0 International License.
 * •    Include the URL for, or link to, the license summary at https://creativecommons.org/licenses/by-sa/4.0/deed.hi (and, if possible, to the complete license terms at https://creativecommons.org/licenses/by-sa/4.0/legalcode.
 * For example:
 * "This work uses content from the Sansar Knowledge Base. © 2018 Linden Research, Inc. Licensed under the Creative Commons Attribution 4.0 International License (license summary available at https://creativecommons.org/licenses/by/4.0/ and complete license terms available at https://creativecommons.org/licenses/by/4.0/legalcode)."
 */

/* Start a coroutine to wait for collision events.
 * Which types of collisions are handled may be set on the properties panel for
 * the object when editing the scene.
 */
using Sansar.Simulation;
using Sansar.Script;
using System;

// To get full access to the Object API a script must extend from ObjectScript
public class SceneObjectScriptExample : SceneObjectScript
{
    // Components can be set in the editor if the correct component types are added to the object
    [EditorVisible]
    private RigidBodyComponent RigidBody = null;

    [DefaultValue(true)]
    [DisplayName("Track Avatar Hits")]
    [EditorVisible]
    private bool TrackAgentHits = true;

    [DefaultValue(true)]
    [DisplayName("Track Object Hits")]
    [EditorVisible]
    private bool TrackObjectHits = true;

    public SceneObjectScriptExample()
    {
        // Script initialization order:
        //    Constructor (this method)
        //    Set base class members (ObjectScript's ExperienceInfo, SceneInfo, and ObjectPrivate)
        //    Set public fields that were configured at edit time (RigidBody, TrackAgentHist, TrackObjectHits)
        //    Init()
    }

    // Override Init to set up event handlers and start coroutines.
    public override void Init()
    {
        // When unhandled exceptions occur, they may be caught with this event handler.
        // Certain exceptions may not be recoverable at all and may cause the script to
        // immediately be removed.
        Script.UnhandledException += UnhandledException;

        // If the object had its components set in the editor they should now have the member initialized
        // The component can also be found dynamically
        if (RigidBody == null)
        {
            if (!ObjectPrivate.TryGetFirstComponent(out RigidBody))
            {
                // Since object scripts are initialized when the scene loads, no one will actually see this message.
                ScenePrivate.Chat.MessageAllUsers("There is no RigidBodyComponent attached to this object.");
                return;
            }
        }

        // Convert the supplied bools to the correct CollisionEventType to track
        CollisionEventType trackedEvents = 0;
        if (TrackAgentHits)
        {
            trackedEvents |= CollisionEventType.CharacterContact;
        }
        if (TrackObjectHits)
        {
            trackedEvents |= CollisionEventType.RigidBodyContact;
        }

        // StartCoroutine will queue CheckForCollisions to run
        // Arguments after the coroutine method are passed as arguments to the method.
        StartCoroutine(CheckForCollisions, trackedEvents);
    }

    private void CheckForCollisions(CollisionEventType trackedEvents)
    {
        while (true)
        {
            // This will block the coroutine until a collision happens
            CollisionData data = (CollisionData)WaitFor(RigidBody.Subscribe, trackedEvents, Sansar.Script.ComponentId.Invalid);
            if (data.EventType == CollisionEventType.CharacterContact)
            {
                ScenePrivate.Chat.MessageAllUsers("I hit an avatar!");
            }
            else
            {
                ScenePrivate.Chat.MessageAllUsers("I hit an object!");
            }
        }
    }

    private void UnhandledException(object sender, Exception e)
    {
        // Depending on the script scheduling policy, the exception may or may not be recoverable.
        // An unrecoverable exception that can be handled will only be given a short time to run
        // so the handler method needs to be kept small.
        // Any exception thrown from this method will terminate the script regardless of the value
        // of UnhandledExceptionRecoverable
        if (!Script.UnhandledExceptionRecoverable)
        {
            ScenePrivate.Chat.MessageAllUsers("Unrecoverable exception happened, the script will now be removed.");
        }
        else
        {
            ScenePrivate.Chat.MessageAllUsers("This script will be allowed to continue.");
        }
    }
}
```

<p class="api-example-source">Source: <code>Examples/SceneObjectScriptExample.cs</code> in the Sansar 47.10.0 client ScriptApi snapshot.</p>

## Members at a glance

| Kind | Members |
|---|---|
| **Constructors** | [SceneObjectScript](#sceneobjectscript) |
| **Properties** | [AllowedContexts](#allowedcontexts) · [ObjectPrivate](#objectprivate) · [ScenePrivate](#sceneprivate) |

## Constructors

### SceneObjectScript

<div class="api-card">
<span id="M:Sansar.Simulation.SceneObjectScript.#ctor"></span>
<span id="C:Sansar.Simulation.SceneObjectScript()"></span>

```csharp signature
protected SceneObjectScript()
```

This constructor is called before any properties have been set. Override [`ScriptBase.Init`](/scripting/api/sansar.script/scriptbase#init) to initialize the script after properties have been set.

</div>


## Properties

### AllowedContexts

<div class="api-card">
<span id="P:Sansar.Simulation.SceneObjectScript.AllowedContexts"></span>

```csharp signature
protected override sealed Sansar.Script.Reflective.Context AllowedContexts { get; }
```

Internal use only.

</div>

### ObjectPrivate

<div class="api-card">
<span id="P:Sansar.Simulation.SceneObjectScript.ObjectPrivate"></span>

```csharp signature
[Sansar.Script.NonReflective]
public ObjectPrivate ObjectPrivate { protected get; set; }
```

The ObjectPrivate this script is attached to if it is attached to an object.

**Value:** [ObjectPrivate](/scripting/api/sansar.simulation/objectprivate) — The scene object this script is attached to if it is attached to an object, null otherwise.

<details class="api-remarks"><summary>Remarks</summary>

For AgentScripts this is the Agent&#39;s ObjectPrivate of their avatar.

</details>

</div>

### ScenePrivate

<div class="api-card">
<span id="P:Sansar.Simulation.SceneObjectScript.ScenePrivate"></span>

```csharp signature
[Sansar.Script.NonReflective]
public ScenePrivate ScenePrivate { protected get; set; }
```

The Scene API for the Scene this script is a part of if the script is attached to scene content.

**Value:** [ScenePrivate](/scripting/api/sansar.simulation/sceneprivate) — The Scene API for this scene if this script was attached to scene content, null otherwise.

<details class="api-remarks"><summary>Remarks</summary>

This value will be set before Init is called.

</details>

</div>


## Used in examples

- [FollowThePath.cs](/scripting/examples/follow-the-path)
- [MoverExample1.cs](/scripting/examples/mover-examples)
- [MoverExample3.cs](/scripting/examples/mover-examples)
- [RandomMovement.cs](/scripting/examples/random-movement)
- [ReflectiveDetectorExample.cs](/scripting/examples/reflective-detector)
- [ReflectiveTrackerExample.cs](/scripting/examples/reflective-detector)
- [SimpleScriptExample.cs](/scripting/examples/simple-script)
- [StatsExample.cs](/scripting/examples/stats-example)
- [TeleportHotkeys.cs](/scripting/examples/teleport-hotkeys)
- [VisitorTrackerExample.cs](/scripting/examples/visitor-tracker)
- [AdvancedCoroutineExample.cs](https://github.com/Wookey-Technologies/sansar-script-starter/blob/66af8b516b701088d043e4615acfcf5779356604/examples/official/AdvancedCoroutineExample.cs)
- [AgentGravityExample.cs](https://github.com/Wookey-Technologies/sansar-script-starter/blob/66af8b516b701088d043e4615acfcf5779356604/examples/official/AgentGravityExample.cs)

…and 36 more examples in the snapshot.

<p class="api-generated" data-pagefind-ignore>Generated from the Sansar 47.10.0 client ScriptApi snapshot.</p>