# Reflective

Kind: Class · Namespace: Sansar.Script · Assembly: Sansar.Script.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.Script">Namespace <a href="/scripting/api/sansar.script"><code>Sansar.Script</code></a></span>
</div>

<span id="T:Sansar.Script.Reflective"></span>

Base class which provides for simple reflection of methods through a given interface.

```csharp
public class Reflective
```

## Remarks

If the object already implements the interface it will return the object directly. Otherwise an facade class is created to map between public methods and properties. Two scripts which use a Reflective object to communicate via script events are below:

```csharp title="SharedStopwatchReaderExample.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. © 2022 Sansar, 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)."
 */
using Sansar.Simulation;
using Sansar.Script;
using System;

public class ScriptEventSourceExample : SceneObjectScript
{
    #region ResetTime
    // This is the event interface that this script will use. Only the public methods and properties
    // that will be referenced are used.
    public interface ResetTime 
    {
        // The current start time.
        // The setter is not public so this script will only ask for the getter
        DateTime StartTime { get; }

        // The calculated elapsed time
        TimeSpan Elapsed { get; }
    }
    #endregion ResetTime

    #region EditorProperties
    [DefaultValue("request")]
    public readonly string requestCommand = "request";

    [DefaultValue("elapsed")]
    public readonly string elapsedCommand = "elapsed";

    [DefaultValue("reset")]
    public readonly string resetCommand = "reset";

    [DefaultValue(3)]
    public readonly double resetMinutes = .2;
    #endregion EditorProperties

    #region EventHandlers

    private void elapsed(ScriptEventData elapsed)
    {
        if(elapsed.Data == null)
        {
            Log.Write(LogLevel.Warning, Script.ID.ToString(), "Expected non-null event data");
            return;
        }
        ResetTime resetTime = elapsed.Data.AsInterface<ResetTime>();

        if(resetTime == null)
        {
            Log.Write(LogLevel.Error, Script.ID.ToString(), "Unable to create interface, check logs for missing member(s)");
            return;
        }

        Log.Write(LogLevel.Info, Script.ID.ToString(), $"Elapsed time = {resetTime.Elapsed} since {resetTime.StartTime}");
    }

    #endregion EventHandlers

    public override void Init()
    {
        // write this script id to the log to track messages
        Log.Write(LogLevel.Info, Script.ID.ToString(), nameof(ScriptEventSourceExample));

        // Subscribe to elapsed messages
        SubscribeToScriptEvent(elapsedCommand, elapsed);

        // set up a timer to periodically reset the elapsed time
        Timer.Create(TimeSpan.FromMinutes(resetMinutes),
            TimeSpan.FromMinutes(resetMinutes),
            () => PostScriptEvent(resetCommand));
        
    }


}
```

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

## Example

```csharp title="SharedStopwatchExample.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. © 2022 Sansar, 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)."
 */
using Sansar.Simulation;
using Sansar.Script;
using System;
using System.Diagnostics;

// This class is a simple stopwatch that can respond to requests for the current elapsed time
// and resets. The elapsed time is also broadcast periodically.
public class SharedStopwatchExample : SceneObjectScript
{
    #region ResetTime
    // This is the event object. Setting the base class to Reflective allows access to the public 
    // properties and methods without needing a reference to this script
    public class ResetTime : Reflective
    {
        // The id of the script which made the last reset request.
        // The setter is made internal so that our script can call
        // it but other scripts cannot.
        public ScriptId SourceScriptId { get; internal set; }
        
        // The current start time.
        // The setter is made internal so that our script can call
        // it but other scripts cannot.
        public long StartTime { get; internal set; }

        // The calculated elapsed time
        public TimeSpan Elapsed
        {
            get
            {
                return TimeSpan.FromTicks(Stopwatch.GetTimestamp() - StartTime);
            }
        }
        // The count of times the timer has been reset
        // The setter is made internal so that our script can call
        // it but other scripts cannot.
        public int ResetCount { get; internal set; }
    }
    #endregion ResetTime

    #region EditorProperties
    [DefaultValue("request")]
    public readonly string requestCommand = "request";

    [DefaultValue("elapsed")]
    public readonly string elapsedCommand = "elapsed";

    [DefaultValue("reset")]
    public readonly string resetCommand = "reset";

    [DefaultValue(1)]
    public readonly double broadcastMinutes = .15;
    #endregion EditorProperties

    #region EventHandlers
    // Handler for the requestCommand, sends the current information back to the requesting script
    private void requestElapsed(ScriptEventData uptime)
    {
        sendElapsed(uptime.SourceScriptId);
    }

    // Handler for the resetCommand, resets the start time
    private void resetElapsed(ScriptEventData uptime)
    {
        resetElapsed(uptime.SourceScriptId);
    }
    #endregion EventHandlers

    #region Implementation

    // Object which tracks all the info we need
    private ResetTime resetTime = new ResetTime();

    // Posts the current time information to the given script id
    // targetScriptId will be AllScripts for the broadcast
    private void sendElapsed(ScriptId targetScriptId)
    {
        PostScriptEvent(targetScriptId, elapsedCommand, resetTime);
    }

    // Resets the elapsed time and tracks the id of the script making the request
    private void resetElapsed(ScriptId id)
    {
        Log.Write(LogLevel.Info, Script.ID.ToString(), $"reset requested by script {id}");
        resetTime.SourceScriptId = id;
        resetTime.StartTime = Stopwatch.GetTimestamp();
        resetTime.ResetCount++;
    }
    #endregion Implementation

    #region Overrides
    public override void Init()
    {
        // write this script id to the log to track messages
        Log.Write(LogLevel.Info, Script.ID.ToString(), nameof(SharedStopwatchExample));

        // sets the initial timer and script id to this script
        resetElapsed(Script.ID);

        // listen for direct requests for the elapsed time
        SubscribeToScriptEvent(requestCommand, requestElapsed);

        // listen for requests to reset the time
        SubscribeToScriptEvent(resetCommand, resetElapsed);

        // set up a timer that broadcasts the elapsed time
        Timer.Create(TimeSpan.FromMinutes(broadcastMinutes), 
            TimeSpan.FromMinutes(broadcastMinutes), 
            () => sendElapsed(ScriptId.AllScripts));
    }
    #endregion Overrides

}
```

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

## Members at a glance

| Kind | Members |
|---|---|
| **Constructors** | [Reflective](#reflective) |
| **Properties** | [AllowedContexts](#allowedcontexts) · [ReflectiveContexts](#reflectivecontexts) · [ReflectiveName](#reflectivename) |
| **Methods** | [AsInterface](#asinterface) · [FullInterface](#fullinterface) · [Register](#register) · [Unregister](#unregister) |

## Constructors

### Reflective

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

```csharp signature
protected Reflective()
```

Default constructor.

</div>


## Properties

### AllowedContexts

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

```csharp signature
protected virtual Reflective.Context AllowedContexts { get; }
```

Internal Use Only. Overridden by subclasses to return only those contexts requested which are allowed for that type of script.

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

Used internally to prevent visiting guest scripts from registering as &#39;scene level&#39; APIs.

</details>

</div>

### ReflectiveContexts

<div class="api-card">
<span id="P:Sansar.Script.Reflective.ReflectiveContexts"></span>

```csharp signature
[Sansar.Script.NonReflective]
protected virtual Reflective.Context ReflectiveContexts { get; }
```

Override ReflectiveContexts to limit which contexts this Reflective interface is available in when registered with.

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

This can be used to further restrict which contexts an interface is available in. It can not be used to register for a context not allowed by the running script type. SceneObjectScript allows ScenePrivate, ScenePublic, ObjectPrivate. ObjectScript allows ObjectPrivate. Overriding this will automatically register this Reflective

</details>

</div>

### ReflectiveName

<div class="api-card">
<span id="P:Sansar.Script.Reflective.ReflectiveName"></span>

```csharp signature
[Sansar.Script.NonReflective]
protected virtual string ReflectiveName { get; }
```

Override ReflectiveName to change which name this class will be registered as in the Reflective system.

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

Defaults to GetType().FullName

</details>

</div>


## Methods

### AsInterface

<div class="api-card">
<span id="M:Sansar.Script.Reflective.AsInterface``1"></span>
<span id="M:Sansar.Script.Reflective.AsInterface``1()"></span>

```csharp signature
[Sansar.Script.NonReflective]
public TInterface AsInterface<TInterface>() where TInterface : class
```

Returns a TInterface object if one can be created, null otherwise

**Type parameters:** `TInterface`: The interface describing the methods and properties desired.

**Returns:** TInterface — A TInterface instance if this object is compatible. An object is compatible if it implements the interface or has public methods and properties which match TInterface.

</div>

### FullInterface

<div class="api-card">
<span id="M:Sansar.Script.Reflective.FullInterface(System.String)"></span>

```csharp signature
[Sansar.Script.NonReflective]
public string FullInterface(string interfaceName)
```

Generates a string which shows all the members which can be reflected.

| Parameter | Type | Description |
|---|---|---|
| `interfaceName` | [string](https://learn.microsoft.com/dotnet/api/system.string) | The name to give the generated interface class in the output. |

**Returns:** [string](https://learn.microsoft.com/dotnet/api/system.string) — The generated string. If no members can be reflected, returns the empty string

</div>

### Register

<div class="api-card">
<span id="M:Sansar.Script.Reflective.Register"></span>
<span id="M:Sansar.Script.Reflective.Register()"></span>

```csharp signature
[Sansar.Script.NonReflective]
public void Register()
```

Register this object to be found with `ScenePrivate.FindReflective`

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

Will register this reflective object with [`Reflective.AllowedContexts`](/scripting/api/sansar.script/reflective#allowedcontexts) if overridden, otherwise with ScenePrivate and ObjectPrivate.

</details>

</div>

### Unregister

<div class="api-card">
<span id="M:Sansar.Script.Reflective.Unregister"></span>
<span id="M:Sansar.Script.Reflective.Unregister()"></span>

```csharp signature
[Sansar.Script.NonReflective]
public void Unregister()
```

Unregister this object so it will not be found with `ScenePrivate.FindReflective`

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

If the Reflective object has not previously been registered nothing happens.

</details>

</div>


## Used in examples

- [ReflectiveDetectorExample.cs](/scripting/examples/reflective-detector)
- [CoroutineLockExample.cs](https://github.com/Wookey-Technologies/sansar-script-starter/blob/66af8b516b701088d043e4615acfcf5779356604/examples/official/CoroutineLockExample.cs)
- [ScriptLibrary/LibraryBase.cs](https://github.com/Wookey-Technologies/sansar-script-starter/blob/66af8b516b701088d043e4615acfcf5779356604/examples/official/ScriptLibrary/LibraryBase.cs)
- [SharedStopwatchExample.cs](https://github.com/Wookey-Technologies/sansar-script-starter/blob/66af8b516b701088d043e4615acfcf5779356604/examples/official/SharedStopwatchExample.cs)

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