> This is part 1 of 2 of the full documentation (pages 1–100 of 115).
> The content is paginated: fetch every part to see all of it.
> Next part: https://docs.airship.gg/llms-full.txt/1
> Page index: https://docs.airship.gg/llms.txt

# Welcome to Airship

Airship games are multiplayer, cross-platform and built with Unity.&#x20;

Games are written in TypeScript and have access to nearly all of the Unity API plus the helpful Airship API. It looks like this:

```typescript
export default class CubeSpinner extends AirshipBehaviour {
    public rotation = new Vector3(1, 1, 0.5);
    
    Update(dt: number) {
        this.transform.Rotate(this.rotation.mul(dt));
    }
}
```


# Installing Airship

## Prerequisites&#x20;

1. Install the "LTS" version of [Nodejs](https://nodejs.org/en)&#x20;
2. Install [Unity Hub](https://unity.com/download)
3. Recommended: install [VSCode](https://code.visualstudio.com/) for script editing

### Download from Github

[Click here to download the Starter Template](https://github.com/easy-games/airship-template/archive/refs/heads/main.zip).&#x20;

This project has everything prepared to start building a game on Airship.&#x20;

* Make sure to unzip after downloading.
* After unzipping, **rename the airship-template-main folder** to the name of your project.<br>

### Open in Unity Hub

1. Add -> Add project from disk.<br>

   <figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FCa7xat4PnMDhAPc6hwke%2FScreenshot%202024-03-12%20at%207.42.06%E2%80%AFAM.png?alt=media&amp;token=58d8d084-3cc8-4bcc-9217-b11e4dbe20f8" alt=""><figcaption></figcaption></figure>
2. Select the unzipped (and renamed!) Starter Template folder.
3. You will be prompted to install a recommended version of Unity for the project. Press yes.

### Opening Unity for the First Time

* You will be prompted to download the Unity Editor. Press yes.&#x20;
  * Make sure to install the required modules:
    * Android Build Support
    * iOS Build Support
    * Linux Build Support (IL2CPP)
    * Windows Build Support (IL2CPP)
    * Mac Build Support (Mono)

<div align="left"><figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2F1AjTLOgUuXoT0lpaIIgJ%2Fimage.png?alt=media&amp;token=4b2ef47e-67aa-4872-adc6-4a24de947dd7" alt="" width="375"><figcaption></figcaption></figure></div>

{% hint style="info" %}
Airship will start downloading required asset packages. This may take a few minutes.&#x20;
{% endhint %}

If you see an LTS error you may need to restart Unity Hub. Close Unity, and Unity Hub and then reopen Unity Hub and your template project.

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FR7bUmAMRSPkRof5PaREr%2Fimage.png?alt=media&amp;token=853319f8-1cfe-4be4-9a2c-a4dad62e64df" alt="" width="287"><figcaption></figcaption></figure>

{% hint style="warning" %}
Unity hub may still be open in your system tray. Right click on the unity icon and select "Quit Unity Hub" to fully close it.

<p align="center"><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FoZh6Z0Yhyryj0xcYLTYE%2Fimage.png?alt=media&amp;token=fbe2418b-811f-4bc2-99e3-2277637b6723" alt="" data-size="original"></p>
{% endhint %}

### Play the Game

You're now ready to play the game. Click the play button in Unity.\
You should see a character spawn on an empty floor:

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2Fc823BOcEjiMKkVKm6djs%2FScreenshot%202024-08-16%20at%203.35.32%20PM.png?alt=media&amp;token=c90bf569-d368-4dc3-979e-eb4e0af77df1" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
If your editor is stuck in an "Untitled Scene", search for "DefaultScene" in the project tab and open it.&#x20;
{% endhint %}


# Typescript Overview

In Airship, you write code using TypeScript instead of C#.

&#x20;Most Unity APIs are available. If something is missing ask in our [Discord](https://discord.gg/YqrmGwSg7z) — we'll add it for you.&#x20;

* You do not use C# for any game scripts (only advanced editor scripts)
* TypeScript allows you to instantly update your game on all platforms

## Opening in VSCode

In [VSCode](https://code.visualstudio.com/) choose `File > Open Folder` and select the Assets folder in your project. This will give you proper syntax highlighting and import suggestions. &#x20;

{% hint style="info" %}
It's important to open the "Assets" folder and not the root folder.
{% endhint %}

## Creating Scripts

To create a new script open the `Project` tab and navigate to the `Assets/Code` folder. In here you can see the scripts that control the template.

<img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FEIAiEMWSoF1Tke4Wq6FF%2FScreenshot%202024-08-16%20at%203.51.56%20PM.png?alt=media&amp;token=cbca8c8e-c6db-4c74-aeed-b733a8f13a87" alt="" data-size="original">

In the folder you can create a new script by right clicking and selecting:\
`Create > Airship > Typescript File`

## Important Globals

Useful Airship services can be found under the `Game` `Airship` and `Platform` globals.


# Airship Components

Most game logic is run through AirshipBehaviours. It is our equivalent to [Unity's MonoBehaviour](https://docs.unity3d.com/Manual/class-MonoBehaviour.html).

AirshipBehaviours offer [useful lifecycle methods](/typescript/airshipbehaviour/lifecycles). They are attached to [Game Objects](https://docs.unity3d.com/Manual/class-GameObject.html).&#x20;

{% code fullWidth="false" %}

```typescript
export default class ExampleAirshipBehaviour extends AirshipBehaviour {
	public greeting = "Hello, World!";

	public Start(): void {
		print(this.greeting);
	}
}
```

{% endcode %}

After the file is compiled, it can be added to a Game Object through the **Add Airship Component** menu

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2Fb5z6hSa2ExCmlRnZ3hcY%2FUnity_WW675SfNFb.png?alt=media&amp;token=93c17add-c456-4b1d-ab87-3572f91e9983" alt=""><figcaption></figcaption></figure>

You should see your component added after selecting it:

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2F4rPADj1KAJJZh3Uf6shB%2FUnity_s68gZXlU8G.png?alt=media&amp;token=0e9da4a5-afb1-49f0-b840-e4c20961bd13" alt=""><figcaption></figcaption></figure>

When you run your game, this will print "Hello, World!"&#x20;


# Adding Inspector Properties

## Adding properties to your component

Any `public` marked property that is a valid serializable type in Unity will show up in the inspector for an `AirshipBehaviour` component

```typescript
export default class ExampleAirshipBehaviour extends AirshipBehaviour {
	public exampleString = "Hello, World!";
	public exampleBoolean = true;
	public exampleNumber = 10;
}
```

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FSH0yQcghwNtCq5k65exl%2FUnity_9ozniEfePr.png?alt=media&amp;token=f2bb499f-57c9-468d-95ec-61b5ea7acf50" alt=""><figcaption><p>Woo, properties!</p></figcaption></figure>

If you do not want your properties exposed, you can just specify them as `private` or `protected`. You can also use the `@NonSerializable` attribute decorator (and use `@SerializeField` to show private/protected fields to the inspector!)

### Adding references to Unity and Airship components

You can add references to Unity Objects in the same way as values. If you might not attach a reference in the inspector you should define it as optional with a `?`

<pre class="language-typescript"><code class="lang-typescript"><strong>export default class ExampleAirshipBehaviour extends AirshipBehaviour {
</strong><strong>	// Assume these will be set in inspector
</strong>	public exampleGameObject: GameObject;
	public exampleImage: Image;
	public exampleButton: Button;
	
	// Possibly not set in inspector
	public exampleTransform?: Transform;
	public exampleCanvas?: Canvas;
}
</code></pre>

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2F9lh49pd2pgWHgvsRBHdU%2FUnity_R4BPhc33XU.png?alt=media&amp;token=a1adae11-c7c3-4692-8e96-426284445d77" alt=""><figcaption><p>References to unity objects - nice!</p></figcaption></figure>

{% hint style="info" %}
when referencing an object for Instantiation you must use a Game Object reference. You are not able to directly reference a component until it is instantiated in the scene.&#x20;
{% endhint %}

#### Adding AirshipBehaviour reference properties

Just like our Unity Object references, we can also add references to other `AirshipBehaviour` components. Any defined class that extends `AirshipBehaviour` can be used as a reference.

```typescript
import AnotherAirshipBehaviour from "./AnotherAirshipBehaviour";

export default class ExampleAirshipBehaviour extends AirshipBehaviour {
	public anotherAirshipBehaviour!: AnotherAirshipBehaviour;
}
```

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FxnKD3PArWRAwD8aviZ8k%2FUnity_JK5vQYO37a.png?alt=media&amp;token=4630ee87-ff09-4dfe-b88c-a31012719c77" alt=""><figcaption><p>References to another AirshipBehaviour!</p></figcaption></figure>

### Organizing your properties

You can use attributes to stylize our inspector properties using decorators:

```typescript
export default class ExampleAirshipBehaviour extends AirshipBehaviour {
	@Header("Basic Properties")
	public stringValue = "Hello, World";
	public numberValue = 1;

	@Header("Constrained properties")
	@Range(0, 100) // show a range of 0 to 100 in the inspector
	public numberRangeValue = 10;

	@Multiline(5) // The number here is the number of lines, and is optional
	public mulitlineStringValue = "This has multiple\nLines!";

	@Spacing(10) // Create some extra space before the next section
	@Header("This has a space of 10 above it")
	@Tooltip("This is a tooltip for the property") // explicit tooltips
	public tooltippedValue = 0;
}
```

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FjmoBiFd1xi5xi5vkKDfM%2FUnity_JsbS6pOW0j.png?alt=media&amp;token=98cf1cf7-aaed-4caa-86bb-86258d95e7b4" alt=""><figcaption></figcaption></figure>

### Optionally showing properties

You may want to only show certain properties only \*if\* a condition is met with other properties.

This can be done with `ShowIf` and `HideIf`.

```typescript
export default class ExampleAirshipBehaviour extends AirshipBehaviour {
	public toggleSetting = false;

	@ShowIf("toggleSetting")
	public valueShowOnToggle = "Hello, world!";
}
```

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FDBH11LN5oVTOnUudxLkd%2Fimage.png?alt=media&amp;token=e5af6bbe-d2aa-48a2-b3d2-8428dc74b49f" alt=""><figcaption><p>Property not shown if <code>toggleSetting</code> is false</p></figcaption></figure>

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FVwF0GJ0r5eVD0rfQhZBF%2Fimage.png?alt=media&amp;token=d1fe3b56-662d-4c2d-9de6-a5b7fc426da8" alt=""><figcaption><p>Property shown if <code>toggleSetting</code> is true</p></figcaption></figure>

You can also use the *match* versions of these decorators to show values on certain values, such as with enums:

```typescript
export enum ExampleTargetType {
	Position,
	Transform,
}

export default class ExampleAirshipBehaviour extends AirshipBehaviour {
	public targetType: ExampleTargetType;

	@ShowIf("targetType", ExampleTargetType.Position)
	public targetPosition: Vector3;

	@ShowIf("targetType", ExampleTargetType.Transform)
	public targetTransform: Transform;
}
```

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2Fn0UU1m6NHFxdRu0tIRHt%2Fimage.png?alt=media&amp;token=e0b549f5-212b-49ce-a9df-f9a691451b42" alt=""><figcaption><p>When <code>Position</code> is selected, it uses the Vector3 <code>targetPosition</code></p></figcaption></figure>

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FUsSVjkqebJECYYe2VfVI%2Fimage.png?alt=media&amp;token=f315c711-c504-4cf6-93aa-ebab777096ad" alt=""><figcaption><p>When <code>Transform</code> is selected, uses the Transform <code>targetTransform</code></p></figcaption></figure>

### JSDoc Tooltips

In Airship we support *implicit JSDoc* tooltips - which are generated by JSDoc comments:

{% hint style="warning" %}
**NOTE**:  JSDoc Code blocks, inline code blocks, tables, hyperlinks and images are not supported in the editor and will not show up in the tooltips.
{% endhint %}

```typescript
export default class ExampleBehaviour extends AirshipBehaviour {
	/**
	 * A value that's documented by JSDoc
	 */
	public value = 100;
}
```

Not only does this have the benefit of being documented in your editor:

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2F4cinBh5NHsLjNrNP66wX%2Fimage.png?alt=media&amp;token=36b2a05a-81ac-49ba-9819-3dd953d2ef2d" alt=""><figcaption><p>The JSDoc tooltip in the editor</p></figcaption></figure>

But Airship will also generate a tooltip in-editor with the same formatting:

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2F5WwSsWgAhCmh1dbG8EB6%2Fimage.png?alt=media&amp;token=e9cdd5d6-bba5-42c2-8eba-049fde1692c9" alt=""><figcaption><p>The tooltip generated in the editor</p></figcaption></figure>

Examples of formatting in the tooltips:

```typescript
export default class ExampleBehaviour extends AirshipBehaviour {
	/**
	 * ## This is a heading
	 * **Some bold** and _italicized_ text.
	 *
	 * - List item 1
	 * - List item 2
	 */
	public value = 100;
}
```

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FFnph5fyUOAoGEGdQbpj5%2Fimage.png?alt=media&amp;token=033ec91d-b86c-4b17-9b65-dd0e1c62f56a" alt=""><figcaption><p>Formatted tooltips, just like in the code editor!</p></figcaption></figure>


# AirshipSingleton

In most games you will want to have some managers that are accessible from anywhere in your codebase. We support this with the AirshipSingleton:

```typescript
export default class WalletManager extends AirshipSingleton {
    public money = 0;
    // ...
}
```

An AirshipSingleton inherits from [AirshipBehaviour](/typescript/airshipbehaviour), meaning it can be attached to a Game Object in your scene and expose properties to the inspector. Uniquely, though, it can be used even without being attached to a game object manually.

To grab the instance of a singleton, you can use the static `Get` method on the Singleton from anywhere in your codebase:

```typescript
const myMoney = WalletManager.Get().money;
```

This will find the existing instance (if it exists), or create an instance if it does not.


# Using Component Decorators

Just like with `MonoBehaviour` in Unity, with our `AirshipBehaviour` we can customize a few things

## Customizing the component menu path

In regular Unity, there is the [`AddComponentMenu`](https://docs.unity3d.com/ScriptReference/AddComponentMenu.html) attribute, in Airship it's the `AirshipComponentMenu` decorator.&#x20;

This is useful for organization purposes.

```typescript
@AirshipComponentMenu("Transform/Follow Transform")
export default class FollowTransform extends AirshipBehaviour {
}
```

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FYDHDhf05WqcIrfn0t8Lh%2FUnity_RuIwWdelxC.gif?alt=media&amp;token=2a3b3ebb-bdf2-4d22-82f7-d646c9212aef" alt=""><figcaption><p>Instead of being in the <code>Scripts</code> menu, now it's in <code>Transform</code> :)</p></figcaption></figure>

## Customizing the Icon

{% hint style="danger" %}
This method is deprecated, you can now customize the icon by going to the TypeScript asset file, and in the inspector changing the `Icon` field.
{% endhint %}

By default an `AirshipComponent` has the `AirshipScript` <img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FZCUxKtWBRZ8piI884yq8%2Fimage.png?alt=media&amp;token=2802acfa-319a-4bc5-813c-2f13f8ad39a9" alt="" data-size="line">icon - however this can be changed as like with `MonoBehaviour` scripts

This is done through the `AirshipComponentIcon` decorator. The path should point to a texture in your project.

```typescript
@AirshipComponentMenu("Voyager/Voyager Health")
@AirshipComponentIcon("Assets/Editor/Icons/Health.png")
export default class VoyagerHealthComponent extends AirshipBehaviour {
    // ... code here
}
```

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FTNz52qA4k4BLF2SVPrQh%2Fimage.png?alt=media&amp;token=c5e46302-5f66-498d-9a42-86fd28e5e4da" alt=""><figcaption><p>Note the <em>Heart</em> icon, also the custom title from the component menu</p></figcaption></figure>


# Accessing Other Components

## Get and Add Components

Similar to Unity, accessing other components can be done through the `GetComponent<T>()` method, as well as other component fetching methods, such as `GetComponents<T>()`.

However, to fetch other *AirshipBehaviour* components, you must use the `GetAirshipComponent<T>()` method, et. al.

The same applies for adding components, such as `AddComponent<T>()` and `AddAirshipComponent<T>()`.

```typescript
// File 1
export default class Test extends AirshipBehaviour {}

// File 2
export default class MyComponent extends AirshipBehaviour {
    public Start() {
        // Adding a Unity and Airship component:
        this.gameObject.AddComponent<BoxCollider>();
        this.gameObject.AddAirshipComponent<Test>();
        
        // Get Unity and Airship components:
        const boxCollider = this.gameObject.GetComponent<BoxCollider>();
        const test = this.gameObject.GetAirshipComponent<Test>();
    }
}
```

## Performance Considerations

Fetching components via methods such as `GetComponent` and `GetAirshipComponent` are expensive. Avoid calling these sorts of methods in per-frame code, such as the `Update` method. Instead, cache the result of the call to a variable.

```typescript
export default class MyComponent extends AirshipBehaviour {
    private boxCollider: BoxCollider;
    
    public Start() {
        // Fetch box collider once:
        this.boxCollider = this.gameObject.GetComponent<BoxCollider>();
    }
    
    public Update(dt: number) {
        // Use box collider per-frame:
        const closestToOrigin = this.boxCollider.ClosestPoint(Vector3.zero);
    }
}
```

Alternatively, the above code could expose `boxCollider` as a public variable, in which the variable could be assigned in-editor.


# Lifecycles

AirshipBehaviours share many of the Unity MonoBehaviour lifecycle methods.

Lifecycle methods are automatically called, similar to an event handler, but without the need to explicitly connect them. All lifecycle methods are optional.

For a flowchart of execution order, refer to the [Unity Docs](https://docs.unity3d.com/6000.0/Documentation/Manual/execution-order.html).

## Initialization

### Awake

Called when the component first starts up. This is similar to its constructor. It will only run one time. It will not run until the GameObject is active *and* the component is enabled.

```typescript
class Example extends AirshipBehaviour {
    Awake() {
        // Code
    }
}
```

### OnEnable

Called when the component is enabled. When the component first runs, this will run right after Awake and before Start. This method will also run anytime the component is re-enabled after being disabled.

```typescript
class Example extends AirshipBehaviour {
    OnEnable() {
        // Code
    }
}
```

### Start

Called after Awake and after OnEnabled. Only called once. Generally, most startup code should go here.

```typescript
class Example extends AirshipBehaviour {
    Start() {
        // Code
    }
}
```

## Decommission

### OnDisable

Called when the component is disabled. OnDisable is also called right before OnDestroy.

{% hint style="info" %}
This method will only run if the component is already enabled, i.e. it will never be called if the component was never enabled.
{% endhint %}

```typescript
class Example extends AirshipBehaviour {
    OnDisable() {
        // Code
    }
}
```

### OnDestroy

Called when the component is removed or the GameObject is destroyed.

```typescript
class Example extends AirshipBehaviour {
    OnDestroy() {
        // Code
    }
}
```

## Update Lifecycles

### Update

Called every frame while the component is active. `deltaTime` is the time (in seconds) since the previous update.

```typescript
class Example extends AirshipBehaviour {
    Update(deltaTime: number) {
        // Run code every frame
    }
}
```

{% hint style="info" %}
`deltaTime` is in *scaled* time and is equivalent to `Time.deltaTime`. If unscaled delta time is needed, use `Time.unscaledDeltaTime`.
{% endhint %}

### LateUpdate

Called every frame while the component is active. Equivalent behavior to Update, except all LateUpdate methods are called *after* all Update methods have run.

```typescript
class Example extends AirshipBehaviour {
    LateUpdate(deltaTime: number) {
        // Run code every frame
    }
}
```

### FixedUpdate

Called every physics step. FixedUpdate should be used when doing physics calculations.

```typescript
class Example extends AirshipBehaviour {
    FixedUpdate(deltaTime: number) {
        // Run code every physics step
    }
}
```

{% hint style="info" %}
`deltaTime` is equivalent to `Time.fixedDeltaTime`.
{% endhint %}

{% hint style="info" %}
Using `Time.deltaTime` or `Time.unscaledDeltaTime` within FixedUpdate will return the same value as `Time.fixedDeltaTime` or `Time.fixedUnscaledDeltaTime`. Refer to the [Unity Docs](https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Time-deltaTime.html) for more info.
{% endhint %}

## Collisions

### OnCollisionEnter

Called when a collider or rigidbody attached to the same GameObject as this component starts touching another collider or rigidbody.

```typescript
class Example extends AirshipBehaviour {
    OnCollisionEnter(collision: Collision) {
        // Code
    }
}
```

### OnCollisionStay

Called once per frame while a collision is occurring.

```typescript
class Example extends AirshipBehaviour {
    OnCollisionStay(collision: Collision) {
        // Code
    }
}
```

### OnCollisionExit

Called when a collider or rigidbody attached to the same GameObject as this component stops touching another collider or rigidbody.

```typescript
class Example extends AirshipBehaviour {
    OnCollisionExit(collision: Collision) {
        // Code
    }
}
```

### 2D

For 2D collisions, there is also `OnCollisionEnter2D`, `OnCollisionStay2D`, and `OnCollisionExit2D`. Their methods look identical to the above examples, except with "2D" appended to the name and collision type.

```typescript
class Example extends AirshipBehaviour {
    OnCollisionEnter2D(collision2d: Collision2D) {}
    OnCollisionStay2D(collision2d: Collision2D) {}
    OnCollisionExit2D(collision2d: Collision2D) {}
}
```

## Triggers

Please refer to the [Unity docs](https://docs.unity3d.com/Manual/CollidersOverview.html) for clarification between normal colliders and trigger colliders. Note that the argument provided is still a Collision object.

### OnTriggerEnter

Called when a collider or rigidbody attached to the same GameObject as this component starts touching another collider or rigidbody.

```typescript
class Example extends AirshipBehaviour {
    OnTriggerEnter(collision: Collision) {
        // Code
    }
}
```

### OnTriggerStay

Called once per frame while a collision is occurring.

```typescript
class Example extends AirshipBehaviour {
    OnTriggerStay(collision: Collision) {
        // Code
    }
}
```

### OnTriggerExit

Called when a collider or rigidbody attached to the same GameObject as this component stops touching another collider or rigidbody.

```typescript
class Example extends AirshipBehaviour {
    OnTriggerExit(collision: Collision) {
        // Code
    }
}
```

### 2D

For 2D collisions, there is also `OnTriggerEnter2D`, `OnTriggerStay2D`, and `OnTriggerExit2D`. Their methods look identical to the above examples, except with "2D" appended to the name and collision type.

```typescript
class Example extends AirshipBehaviour {
    OnTriggerEnter2D(collision2d: Collision2D) {}
    OnTriggerStay2D(collision2d: Collision2D) {}
    OnTriggerExit2D(collision2d: Collision2D) {}
}
```


# Airship Scriptable Objects

`AirshipScriptableObject` is a class you can derive from to create objects that live independently of GameObjects.  This allows you to save data as an asset to use at runtime.

Like [ScriptableObject](https://docs.unity3d.com/6000.2/Documentation/ScriptReference/ScriptableObject.html) in Unity, they are accessible from scenes and assets within a project.

{% hint style="info" %}
Changing values in a Scriptable Object requires a full publish (as it is an asset) instead of a code publish to update, if you need a value that can be changed via a code publish, you should be storing it in code.
{% endhint %}

{% code fullWidth="false" %}

```typescript
// This will show in Create -> ScriptableObjects -> Example Data Object by default
@CreateAssetMenu()
export default class ExampleDataObject extends AirshipScriptableObject {
    public message = "Hello, world!";
    
    protected Awake() {
         // This will be fired when the scriptable object is first referenced/created.
         // The properties of this object will be set up on Awake
         print(this.message, "from the example scriptable object awake!");   
    }
    
    protected OnDestroy() {
         // This will be called if:
         //  - A CreateInstance() ScriptableObject is destroyed
         print("This object was destroyed!");
    }
}
```

{% endcode %}

This allows you to save data as an asset to use at runtime. This can be useful for global data shared between objects, avoiding the necessity for duplicate data.

### Referencing a ScriptableObject in your game

As an example, we can use a ScriptableObject to create "templates" for NPCs we want to spawn

```typescript
@CreateAssetMenu()
export default class NPCTemplate extends AirshipScriptableObject {
	@Header("Metadata")
	public name = "Example NPC";
	@Min(1)
	public maxHealth = 100;

	@Header("Appearance")
	public customPrefab?: GameObject;
}
```

Then we can create it using the menu item:

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FBfc39kscVMG7UkMdETNU%2Fimage.png?alt=media&amp;token=6ebb97ec-42b6-4721-9b75-92f05de56d69" alt="" width="536"><figcaption><p>Since NPCTemplate has <code>CreateAssetMenu</code> on it, it will show up here by default.</p></figcaption></figure>

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FA1x2cRr5q8NoGaauwHvJ%2Fimage.png?alt=media&amp;token=c542f34d-b488-4b02-852e-bf2c1a9560fd" alt=""><figcaption><p>The resulting ScriptableObject - we can now set a name, the health and even a custom prefab if need be.</p></figcaption></figure>

Then to reference the ScriptableObject

```typescript
import { Airship } from "@Easy/Core/Shared/Airship";
import NPCTemplate from "Code/ScriptableObjects/NPCTemplate";

export default class NPCCharacterSpawner extends AirshipBehaviour {
	// Just like referencing other AirshipBehaviours
	// We can also reference AirshipScriptableObject classes
	public template: NPCTemplate;

	@Server()
	protected Start(): void {
		if (this.template === undefined) return;

		const character = Airship.Characters.SpawnNonPlayerCharacter(this.transform.position, {
			customCharacterTemplate: this.template.customPrefab,
		});

		character.SetMaxHealth(this.template.maxHealth);
		character.SeatHealth(this.template.maxHealth);
		character.SetDisplayName(this.template.name);
	}
}
```

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2F0gXf9R1LdHUbYtWfrXwS%2Fimage.png?alt=media&amp;token=d4d589f9-ae47-4a40-8f9d-6b2f8a2476e4" alt=""><figcaption><p>You will see we now have a reference field for an NPC template</p></figcaption></figure>

Then click on the <kbd>None (NPC Template)</kbd> <i class="fa-circle-o">:circle-o:</i> button - and it will give you a prompt to select a scriptable object of that type, which we can then select -

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FByVplWTstUFQBI5fwbaT%2Fimage.png?alt=media&amp;token=0f6bb4bc-6a23-4f5d-bff2-011b8c6653e6" alt=""><figcaption><p>The template is now provided</p></figcaption></figure>

Then when you run the game - it spawns the NPC with the name and health!

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FsFlyCR5xQyjig5j8pVvD%2Fimage.png?alt=media&amp;token=b941c732-3cdd-4e99-be67-13578f29755d" alt="" width="310"><figcaption><p>The spawner in action</p></figcaption></figure>

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FHbEjny4GGCLFHp029agb%2Fimage.png?alt=media&amp;token=c206d69d-7ee3-4eb6-8467-2c52e531a4f5" alt="" width="375"><figcaption><p>Example of using the same scriptable object with multiple spawners</p></figcaption></figure>


# Server-only/Client-only code

How to strip code from the server or client, making code server or client only.

When developing a game in Airship, it may be prudent to not have server logic on the client. For example, if you have an anti-cheat system or other code that the client should not know about.&#x20;

{% hint style="danger" %}
Even with server only code, it's recommended *to **not*** store API keys or any other sensitive data in your components or scripts.

* **Properties**: Properties are serialized regardless of server or client, so are accessible by the client.
* Through a server-only *getter*: They will still be accessible to anyone who has access to your source code.&#x20;
  {% endhint %}

## Method 1: Server-only/Client-only methods

Inside `AirshipBehaviour` classes, you can use the `@Server()` and `@Client()` [method decorators](https://www.typescriptlang.org/docs/handbook/decorators.html#method-decorators) to tell the compiler you want the given methods to be server or client only.

```typescript
export default class ServerAndClientOnlyMethods extends AirshipBehaviour {
    @Server()
    public ServerOnlyMethod() {
        print("This will only be on, and callable by the server!")
    }
    
    @Client()
    public ClientOnlyMethod() {
        print("This will only be on, and callable by the client!");
    }
}
```

{% hint style="warning" %}
If you try to use a server-only method on the client, or a client-only method on the server, it will error.

However, there is an exception to this rule: Lifecycle methods such as `Awake`, `Start`, `OnCollisionEnter` etc; as this allows then to make those lifecycles server or client only without throwing an error.
{% endhint %}

### Server/Client only lifecycle methods

Lifecycle methods may also be designated as server or client only. In the example below, the Start lifecycle method automatically runs on the server but not on the client.

```typescript
export default class ServerComponent extends AirshipBehaviour {
    @Server()
    protected Start() {
         print("I am a server component, printing hello from the server!");   
    }
}
```

## Method 2: Conditional directives

There may be cases you want to mark blocks of code server/client only rather than entire functions. This will work even if it's not inside an `AirshipBehaviour`. To do this, we use *directives*. There are two directives:

* `$SERVER` - when in a condition, will check if it's the server
* `$CLIENT` - when in a condition, will check if it's the client

{% hint style="warning" %}
The compiler will also try to implicitly turn `Game.IsServer()` and `Game.IsClient()` calls if it can into these if `airship.stripImplicitContextCalls` is `true` (enabled by default currently) in `tsconfig.json` - this is more for backwards compatibility and it's recommended you use the actual directives above if your intention is to strip the code.
{% endhint %}

```typescript
export default class DirectivesExample extends AirshipBehaviour {
    protected Start() {
       // You can use directives within ternaries!
       const contextGreeting = $SERVER ? "Hi I'm the server" : "Hi I'm the client!";
    
       // this will print different depending on server or client! :D
       print(contextGreeting);
    
       // Server only code block
       if ($SERVER) {
          print("This will only show up in server code, and print on the server!");
       }
       
       // Client only code block
       if ($CLIENT) {
          print("This will only show up in client code, and print on the client!");
       } else {
          // Of course you can also use else for the opposite!
          print("This will show up in server code and print on the server!");
       }
       
       // Dedicated server block (no shared mode)
       if ($SERVER && !$CLIENT) {
          print("This will only be on a dedicated server (no shared mode)");
       }
       
       // Dedicated client block (no shared mode)
       if ($CLIENT && !$SERVER) {
          print("This will only be on a dedicated client (no shared mode)")
       }
    }
}
```

You can mix these with the decorators as well, to do cool things like create server/client lifecycle event methods:

```typescript
export default class MyComponent extends AirshipBehaviour {
    protected Start() {
        // It will call 'StartServer' on the server!
        if ($SERVER) this.StartServer();
        // It will call 'StartClient' on the client!
        if ($CLIENT) this.StartClient();
    }
    
    @Server() // server start method :D
    protected StartServer() {
        print("Hello, server!");
    }
    
    @Client() // client start method :D
    protected StartClient() {
        print("Hello, client!");
    }
}
```


# Compiler JSDoc Modifiers

Since *TypeScript* does not support decorators on anything but classes, class fields and class methods, you can use the following JSDoc *modifiers* to apply some customization:

### InspectorName

To change the name of an enum member, akin to unity's [InspectorNameAttribute](https://docs.unity3d.com/6000.0/Documentation/ScriptReference/InspectorNameAttribute.html):

```typescript
export enum ModelImporterIndexFormat {
    Auto,
    /** @InspectorName 16 bits **/
    UInt16,
    /** @InspectorName 32 bits **/
    UInt32,
}
```

{% hint style="warning" %}
Do note *currently* with the editor API, this will also affect the name of the enum values.
{% endhint %}

### Flags

To mark an enum as a flag enum, you can use `@flags`

```typescript
/** @flags */
export enum ExampleFlags {
    A = 1,
    B = 2,
    C = 4,
    D = 8,
    E = 16,
    // ...
}
```

Do note that if it doesn't follow powers of 2, it will fall back to an integer enum.


# Multiplayer

All games on Airship are multiplayer by default.

## Game Servers

When published, your game automatically runs with a dedicated server. This means your entire Unity project will run on the game server just as it runs on clients. Your game server will manage connecting clients and set them up as [players](https://ref.airship.gg/classes/Player.html).

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FbCNdLdld6VASoXeso71Y%2FMultiplayer%20(2).png?alt=media&amp;token=efe71fa5-28a0-4c28-98e3-afe2250b676b" alt="" width="371"><figcaption></figcaption></figure>

A game server should be responsible for storing game state (such as how many coins each player has) and communicating that state to all connected players.

{% hint style="info" %}
For server ↔ client data communication see [`NetworkSignal`](/networking/network-signals)
{% endhint %}


# Local Server Mode

We have two formats for server mode during local development: [Dedicated](#dedicated) and [Shared](#shared). You can swap your development mode by pressing the toggle left of the play button:

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FXN2D4JFa6MdmOt5UuVf3%2FScreenshot%202024-07-03%20at%202.41.36%20PM.png?alt=media&amp;token=aaaf25f0-de45-4933-becc-8d1a0f09371c" alt="" width="563"><figcaption></figcaption></figure>

## Dedicated

Local development in dedicated mode mimics how a published game will run. In dedicated you will need one Unity editor instance for each connected client and one for the server.

We use **Multiplayer Play Mode** (MPPM) to manage multiple editor windows. Each window represents a different client (with one for the server).

How to setup a dedicated server using MPPM:

1. Open menu item `Window > Multiplayer Play Mode`
2. Tag Player 2 with Server (`Add Tags for Player > Server`)
3. Check the box left of Player 2 (this should open your server window)

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2Fo6gQXL5hO90ra0rwHp24%2FScreenshot%202024-07-03%20at%201.56.01%20PM.png?alt=media&amp;token=97fd70a4-5454-4ccf-9bf8-609fc19e621d" alt="" width="375"><figcaption></figcaption></figure>

## Shared

Shared mode doesn't require multiple editor windows. Instead, your single window will function as both the client and server. Both `Game.IsServer()` and `Game.IsClient()` will return `true`. This is useful because time-to-play becomes faster. The downside is that the game behaves differently in editor than when published on a dedicated server.&#x20;

{% hint style="warning" %}
Shared mode will behave differently from a published game. You should make sure to test your game in dedicated before publishing.
{% endhint %}


# Network Signals

[Network Signals](#network-signals) are used to communicate between the client and server. They are a critical piece of building a multiplayer game.&#x20;

***

## Overview

Imagine a scenario where a player would like to use a health potion. We first need to tell the server that a player would like to use a potion and have it apply the potion's effects.

{% code title="PotionManager.ts" lineNumbers="true" fullWidth="false" %}

```typescript
export default class PotionManager extends AirshipSingleton {
    // Creating a NetworkSignal
    private usePotion = new NetworkSignal<{ potion: string }>("UsePotion");

    public override Start(): void {
        if (Game.IsClient()) {
            // Tell the server that the local player is trying to use a potion
            this.usePotion.client.FireServer({ potion: "health" });
        }

        if (Game.IsServer()) {
            // Listen for a player use potion request
            this.usePotion.server.OnClientEvent((player, event) => {
                const hasPotion = DoesPlayerHavePotion(player, event.potion);
                if (!hasPotion) return;
                // Apply the potion's effect
                player.character?.SetHealth(100);
            });
        }
    }
}
```

{% endcode %}

***

## Network Signals

#### Example Use Cases

{% tabs %}
{% tab title="Client -> Server" %}

<table><thead><tr><th>Example</th><th>Explanation</th><th data-hidden></th></tr></thead><tbody><tr><td>Ability Use</td><td>Notifying the server when a player uses a special ability</td><td></td></tr><tr><td>Trade Request</td><td>Letting the server know two players would like to trade</td><td></td></tr><tr><td>Item Drop</td><td>Telling the server a player has dropped an item</td><td></td></tr></tbody></table>
{% endtab %}

{% tab title="Server -> Client" %}

| Example             | Explanation                                                                    |
| ------------------- | ------------------------------------------------------------------------------ |
| Weather Change      | Informing clients of a weather change to keep them visually synchronized       |
| Leaderboard Updates | Letting clients know the latest leaderboard standings                          |
| Status Effects      | Communicating that a client has had a status effect applied to their character |
| {% endtab %}        |                                                                                |
| {% endtabs %}       |                                                                                |

### Creating a Network Signal

Network Signals can be created inside of any script. `NetworkSignal` takes a single generic parameter that is the type of data passed through the signal.

<pre class="language-typescript" data-title="Shared" data-line-numbers data-full-width="false"><code class="lang-typescript"><strong>const usePotion = new NetworkSignal&#x3C;{ potion: string }>("UsePotion");
</strong></code></pre>

{% hint style="info" %}
The `NetworkSignal` constructor accepts a single `string` parameter that uniquely identifies the signal. Providing a string that is already in use will raise an error when entering play mode.
{% endhint %}

***

### Client -> Server

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FyGpRXiMNoHeMMm7RcQHS%2FRemoteEventClient.png?alt=media&amp;token=564dfd59-d09b-4405-855a-f160ca03cf71" alt="" width="371"><figcaption><p>Network Signal: Client -> Server</p></figcaption></figure>

Firing the `usePotion` Network Signal on the client

{% code title="Client" lineNumbers="true" %}

```typescript
usePotion.client.FireServer({ potion: "health" });
```

{% endcode %}

Listening for `usePotion` Network Signals on the server

{% code title="Server" lineNumbers="true" %}

```typescript
usePotion.server.OnClientEvent((player, event) => {
    print(`${player.username} is using potion: ${event.potion}`);
});
```

{% endcode %}

The first argument passed to `OnClientEvent` is always the [`Player` ](https://ref.airship.gg/classes/Player.html)who fired the Network Signal.

***

### Server -> Client

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FGpizbIqEovUtELl5mtoY%2FRemoteEventServer.png?alt=media&amp;token=a7109ca7-e056-4424-b569-3a4f618cba92" alt="" width="371"><figcaption><p>Network Signal: Server -> Client(s)</p></figcaption></figure>

Once the server has applied the potion, we want to tell every player about it so they can play particle effects, sounds, update UI, etc.

Server to client Network Signals can be sent to any number of players

{% code title="Shared" lineNumbers="true" %}

```typescript
const potionUsed 
    = new NetworkSignal<{ userId: string; potion: string }>("PotionUsed");
```

{% endcode %}

Telling all players a potion has been consumed

{% code title="Server" lineNumbers="true" %}

```typescript
potionUsed.server.FireAllClients({ userId: "1", potion: "health" });
```

{% endcode %}

Listening for `potionUsed` Network Signals on the client

{% code title="Client" lineNumbers="true" %}

```typescript
potionUsed.client.OnServerEvent((event) => {
    print(`User ${event.userId} has used potion: ${event.potion}`);
});
```

{% endcode %}

***

## Data Limitations

Primitive data types and their composite forms (arrays, objects) can be sent over the network when using `NetworkSignals` and `NetworkFunctions`.  The following Unity types are also supported

* [Vector3](https://docs.unity3d.com/ScriptReference/Vector3.html)
* [Vector2](https://docs.unity3d.com/ScriptReference/Vector2.html)
* [Quaternion](https://docs.unity3d.com/ScriptReference/Quaternion.html)
* [Color](https://docs.unity3d.com/ScriptReference/Color.html)

{% hint style="info" %}
A common requirement is sending Characters and Players over the network. Send [Player ](https://ref.airship.gg/classes/Player.html)and [Character](https://ref.airship.gg/classes/Character.html) ids and utilize the [Player](https://ref.airship.gg/classes/PlayersSingleton.html) and [Character](https://ref.airship.gg/classes/CharactersSingleton.html) APIs to fetch their respective objects. This ensures that only permitted data types are sent over the network, while the actual player and character objects are retrieved locally.
{% endhint %}

## Caching

If a network signal receives an event, but does not have any existing connection handlers, the event will be cached until the first connection is created. At this point, all events will be passed along to the connection handler.

This is typically useful when the server sends a client a network signal event right after the client has joined, but before the client has connected to the signal. Thus, the event is not missed by the client, as it is successfully handed to the first connection to the signal on the client.

The cache is limited in size (currently hard-coded to 10,000), and will throw errors if exceeded.


# Network Identity

The [NetworkIdentity](#networkidentity) component enables you to spawn `GameObjects` on the server and have them automatically appear on each client.

***

## Overview

{% code title="CubeManager.ts" lineNumbers="true" %}

```typescript
export default class CubeManager extends AirshipSingleton {
    // This is a reference to a prefab with a NetworkIdentity component
    public Cube: GameObject;

    public override Start(): void {
        if (Game.IsServer()) {
            // Spawn a cube on the server and replicate it to each player
            const cube = Object.Instantiate(
                this.Cube, 
                new Vector3(0, 1, 0), 
                Quaternion.identity
            );
            NetworkServer.Spawn(cube);
            // Despawn cube after 4 seconds
            task.delay(4, () => NetworkServer.Destroy(cube));
        }
    }
}
```

{% endcode %}

{% embed url="<https://drive.google.com/file/d/1Q34c-3ZSqkNgM-iglk6TrMxjZZVyhM52/view?usp=drive_link>" %}
Spawning and despawning a NetworkIdentity
{% endembed %}

## NetworkIdentity

### Attaching a NetworkIdentity Component

The `NetworkIdentity` component can be added to any [`GameObject`](https://docs.unity3d.com/ScriptReference/GameObject.html) through the "Add Component" menu.

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FdHnol1M9fyBqK7Nw9cUC%2Fnetworkidentity.png?alt=media&amp;token=48a95646-b35d-45c5-9209-32bb94003015" alt=""><figcaption><p>Adding a NetworkIdentity component to a prefab</p></figcaption></figure>

***

### Adding a NetworkIdentity to a NetworkPrefabCollection

In order to be able to spawn and despawn a `NetworkIdentity` through code, it must be a part of a game's NetworkPrefabCollection. The template project includes a collection in the `Assets/Resources` folder.

If your project does **not** already contain a collection, you can automatically generate one through the "Generate Network Prefab Collections" menu item.

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FFDieoTy7HWzfLx8GzVXY%2Fgenerate.png?alt=media&amp;token=4a49faa3-56e2-4891-855d-6e01e07fad87" alt=""><figcaption><p>Generating a NetworkPrefabCollection</p></figcaption></figure>

{% hint style="info" %}
When a NetworkPrefabCollection is generated, it is automatically populated with every prefab in the project that contains a [NetworkIdentity](#networkidentity).  For smaller projects, this tool can be used to entirely manage a game's collection. If a game has a large amount of assets, developers should opt to manually add new prefabs to their game's collection.
{% endhint %}

To add a `NetworkIdentity` to your game's NetworkPrefabCollection, drag a prefab from your Hierarchy or Project tab onto the NetworkPrefabCollection "Network Prefabs" list, or select the prefab through the search menu.

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2Fw2PQiMVKjstJWEgebqUB%2Fadd-to-collection.png?alt=media&amp;token=a2b00eba-8ef8-4739-8dd4-7b2abd62320f" alt="" width="422"><figcaption><p>Adding a prefab to a NetworkPrefabCollection</p></figcaption></figure>

***

### Spawning a NetworkIdentity

{% code title="Server" lineNumbers="true" %}

```typescript
const cube = Object.Instantiate(cubePrefab);
NetworkServer.Spawn(cube);
```

{% endcode %}

{% hint style="success" %}
When a player joins a game all networked `GameObjects` in the server scene are automatically replicated to the player.
{% endhint %}

***

### Despawning a NetworkIdentity

{% code title="Server" lineNumbers="true" %}

```typescript
NetworkServer.Destroy(cube);
```

{% endcode %}

***

### Sending a NetworkIdentity over network

You can use `networkIdentity.netId` to send a reference to a NetworkIdentity via NetworkSignals and NetworkFunctions.

Use `NetworkUtil.GetNetworkIdentity(netId)` to retrieve a NetworkIdentity from the netId.&#x20;


# Network Transform

The NetworkTransform component allows you to position, rotate, and scale GameObjects on the server and have the changes automatically applied on each player's client.

***

## Overview

{% code title="CubeManager.ts" lineNumbers="true" %}

```typescript
export default class CubeManager extends AirshipSingleton {
    // This is a reference to a prefab with NetworkIdentity and NetworkTransform
    // components
    public Cube: GameObject;
    // This is a reference to an instantiated cube
    private cubeInstance?: GameObject;

    public override Start(): void {
        if (!Game.IsServer()) return;
        // Spawn a cube on the server
        this.cubeInstance = Object.Instantiate(
            this.Cube, 
            new Vector3(0, 1, 0), 
            Quaternion.identity
        );
        NetworkServer.Spawn(this.cubeInstance);
    }

    public override Update(dt: number): void {
        if (!Game.IsServer() || !this.cubeInstance) return;
        // Rotate the cube on the server
        this.cubeInstance.transform.Rotate(Vector3.up, 10 * dt);
    }
}
```

{% endcode %}

{% embed url="<https://drive.google.com/file/d/1XBSv0GDBcGJS0BNsKB1_m3trUXhzLmH8/view?usp=drive_link>" %}
Using a NetworkTransform to rotate a GameObject
{% endembed %}

***

## NetworkTransform

### Attaching a NetworkTransform Component

The `NetworkTransform` component can be added to any [`GameObject`](https://docs.unity3d.com/ScriptReference/GameObject.html) through the "Add Component" menu.

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FFRFgqye4ArTQVrJxYdsb%2Fnetworktransform.png?alt=media&amp;token=e1d8dee6-ce91-437c-8964-10200a1c1b27" alt=""><figcaption><p>Adding a NetworkTransform component to a prefab</p></figcaption></figure>

{% hint style="info" %}
`NetworkTransform` requires a [NetworkIdentity ](/networking/network-identity)component to function properly.
{% endhint %}

***

### Network Ownership

When you spawn a NetworkIdentity, you can optionally specify an owner. The player who has ownership of a NetworkIdentity with a [NetworkTransform](#networktransform) component has the authority to control the [Transform](https://docs.unity3d.com/ScriptReference/Transform.html) of the parent GameObject. All Transform updates made by the owner are applied on the server, and then sent to and applied on every other player's client.

{% code title="Server" lineNumbers="true" %}

```typescript
NetworkServer.Spawn(
    this.cubeInstance,
    player.networkIdentity.connectionToClient
);
```

{% endcode %}

On the owner player's client

{% code title="Client" lineNumbers="true" %}

```typescript
cube.transform.position = new Vector3(0, 10, 0);
```

{% endcode %}

This is particularly useful when you want a player to be able to control a non-player entity, such as a spaceship, turret, or a vehicle.


# Network Functions

## Network Functions

Network Functions allow for two-way client to server communication and follow a request and response format.

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FYniF7Llv7dzUTRo3RvPz%2FRemoteFunctions.png?alt=media&amp;token=c2451e90-d2cb-4e64-9bda-0b070577074f" alt=""><figcaption><p>Network Functions</p></figcaption></figure>

## Overview

An example of when a `RemoteFunction` would be appropriate is a player requesting to open a loot crate. First the player tells the server the kind of crate it would like to open, and the server responds with what the player received.

{% code title="CrateManager.ts" lineNumbers="true" fullWidth="false" %}

```typescript
interface CrateResponse {
    item: string;
    rarity: string;
}

export default class CrateManager extends AirshipSingleton {
    // Creating a NetworkFunction
    private open =
        new NetworkFunction<{ crateType: string }, CrateResponse>("LootCrate");

    public override Start(): void {
        if (Game.IsClient()) {
            // Tell the server that you'd like to open a loot crate
            const loot = this.open.client.FireServer({ crateType: "weapon" });
            print(`You received a ${loot.rarity} ${loot.item}`);
        }

        if (Game.IsServer()) {
            // Listen for player crate open requests
            this.openCrate.server.SetCallback((player, event) => {
                return {
                    item: "sword",
                    rarity: "legendary",
                }
            });
        }
    }
}
```

{% endcode %}

***

#### Example Use Cases

{% tabs %}
{% tab title="Client -> Server -> Client" %}

<table><thead><tr><th>Example</th><th>Explanation</th><th data-hidden></th></tr></thead><tbody><tr><td>Purchase Request</td><td>Client requests to purchase an item, server validates the transaction, client is notified of the result</td><td></td></tr></tbody></table>
{% endtab %}

{% tab title="Server -> Client -> Server" %}

<table><thead><tr><th width="350">Example</th><th></th><th data-hidden></th></tr></thead><tbody><tr><td>Prompt Popup</td><td>Server notifies client of a game event, a prompt pops up on client allowing them to choose if they would like to participate, player responds with "Yes" or "No" and server is informed of result</td><td></td></tr></tbody></table>
{% endtab %}
{% endtabs %}

### Creating a Network Function

Like [Network Signals](/networking/network-signals), Network Functions can be created inside of any script. A `NetworkFunction` expects two generic parameters: a request type and response type.

{% code title="Shared" lineNumbers="true" %}

```typescript
interface CrateResponse {
    item: string;
    rarity: string;
}

const openCrate = 
    new NetworkFunction<{ crateType: string }, CrateResponse>("LootCrate");
```

{% endcode %}

***

### Client -> Server -> Client

Firing a Network Function on the client

{% code title="Client" lineNumbers="true" %}

```typescript
const loot = openCrate.client.FireServer({ crateType: "weapon" });
print(`You received a ${loot.rarity} ${loot.item}`);
```

{% endcode %}

Listening to Network Functions on the server

{% code title="Server" lineNumbers="true" %}

```typescript
openCrate.server.SetCallback((player, event) => {
    return {
        item: "sword",
        rarity: "legendary",
    };
});
```

{% endcode %}

`SetCallback`'s first parameter is always the [`Player`](https://ref.airship.gg/classes/Player.html) who fired the network function.

***

### Server -> Client -> Server

Network Functions that originate on the server behave exactly the same.

{% hint style="info" %}
`NetworkFunctions` are synchronous, the active thread will **yield** until the callback returns. Consider wrapping `FireServer` and `FireClient` calls inside of [`task.spawn`](https://ref.airship.gg/functions/task.spawn.html) to avoid interfering with the flow of your game.
{% endhint %}


# AirshipNetworkBehaviour

{% hint style="danger" %}
AirshipNetworkBehaviour is a work-in-progress system. It's not recommended to use this yet. There will likely be breaking changes in the future.

Instead, use NetworkSignals.
{% endhint %}

If your Airship Component requires networking capabilities, we have `AirshipNetworkBehaviour` . This will enable networking remote procedural calls (RPCs), as well as [Networking Lifecycle Events](/networking/airshipnetworkbehaviour/lifecycle-events) to be usable on the component.

{% code fullWidth="false" %}

```typescript
import { AirshipNetworkBehaviour, TargetRpc } from "@Easy/Core/Shared/Network";

export default class ServerWelcomeComponent extends AirshipNetworkBehaviour {
    // This is a client-only "Start" event
    public OnClientStart() {
       print("Hello, Client!");   
    }
    
    // This is a server-only "Start" event
    public OnServerStart() {
       print("Hello, Server!");
       
       Airship.Players.ObservePlayers((player) => {
          // Personalized server introduction :-)
          this.SendServerIntroduction(player, `Hello, World! - to you - ${player.username}!`);
       });
    }
    
    // TargetRpc will only send to the specified player
    // this method will also only invoke on the client it's sent to
    @TargetRpc()
    public SendServerIntroduction(player: Player, message: string) {
       Game.BroadcastMessage(`[SERVER] ${message}`);
    }
}
```

{% endcode %}


# Lifecycle Events

Aside from the usual events in an `AirshipBehaviour`, the network behaviour adds the following you can use:

## General Networking Events

* `OnStartNetwork` - Method called when the object starts networking
* `OnStopNetwork` - Method called when the object stops networking

## Server Only

* `OnStartServer` - Method called when the object starts networking on the server
* `OnOwnershipServer` - Method called when the ownership of an object is changed on the server
* `OnSpawnServer` - Method called when the object spawns on the server
* `OnDespawnServer` - Method called when the object is despawned on the server
* `OnStopServer`  - Method called when the object stops networking on the server

## Client Only

* `OnStartClient` - Method called when the object starts networking on the client
* `OnOwnershipClient` - Method called when the ownership is changed on the client
* `OnStopClient` - Method called when the object stops networking on the client

## Execution Ordering of Events

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2Focx9fUY9eMZgvkn7ZKlF%2FUntitled%20Diagram.drawio(2).png?alt=media&amp;token=6b983192-c457-42a5-97e1-81767ea04d59" alt=""><figcaption><p>The Lifecycle Events of an AirshipNetworkBehaviour</p></figcaption></figure>


# ServerRpc

The server RPC allows logic to be ran on the server from a client - by default it will not require any ownership - so can be run by any player. This wont run on the client who called it unless `RunLocally` is `true`.

{% code fullWidth="false" %}

```typescript
import { AirshipNetworkBehaviour, ServerRpc } from "@Easy/Core/Shared/Network";

export default class ExampleGlobalButton extends AirshipNetworkBehaviour {
    // This will send a button press message to the server _only_
    @ServerRpc()
    public PressButton(player: Player, message: string) {
        // Player argument necessary if not requiring ownership
        print("The player", player, "pressed the button with their message", message);
    }
}
```

{% endcode %}

{% hint style="info" %}
Note: If you want to restrict to only the network owner of the component, you must specify `RequiresOwnership`as `true`

<pre class="language-typescript" data-full-width="true"><code class="lang-typescript">import { AirshipNetworkBehaviour, ServerRpc } from "@Easy/Core/Shared/Network";
<strong>export default class ExamplePlayerInventory extends AirshipNetworkBehaviour {
</strong>    @ServerRpc({ RequiresOwnership: true })
    public DropItemFromInventory(itemId: ItemType, amount: number) {
        // Note: No player argument as this is guaranteed to be the owner
    }
}
</code></pre>

{% endhint %}


# ObserversRpc

### Observers RPC

This is for broadcasting a call to all clients from the server.

<pre class="language-typescript" data-full-width="false"><code class="lang-typescript">import { AirshipNetworkBehaviour, ObserversRpc } from "@Easy/Core/Shared/Network";
<strong>export default class ExampleGlobalButton extends AirshipNetworkBehaviour {
</strong>    @ObserversRpc()
    private BroadcastMessage(string message) {
        print("Server has sent everyone", message, "!")
    }
}
</code></pre>


# TargetRpc

### Target RPC

This is for sending a function call to a specific player

{% code fullWidth="false" %}

```typescript
import { AirshipNetworkBehaviour, TargetRpc } from "@Easy/Core/Shared/Network";
export default class ExampleGlobalButton extends AirshipNetworkBehaviour {
    @TargetRpc()
    public SendMessageToPlayer(player: Player, message: string) {
        print("The server says", message, "!");
    }
    
    OnStartServer() {
        Airship.Players.ObservePlayers((player) => {
            // Will send the message to the specific player
            this.SendMessageToPlayer(player, "Hello, " + player.username + "!");
        });
    }
}
```

{% endcode %}


# Create Dashboard - Game CMS

&#x20;The [Airship Create Dashboard](https://create.airship.gg/) lets you Manage the content of your organizations and games online.

### Organization

Your company or team that will have a set of games and/or packages

### Games

Individual game that Airship players can join

### Packages

Code and graphics that can be used in multiple Unity game projects


# Game Visibility

When you create a game it has a default visibility of `Unlisted` . You can change this at anytime on the [create dashboard](https://create.airship.gg/dashboard/organization/game/listing/).

<table><thead><tr><th width="180">Visibility Mode</th><th>Explanation</th><th data-hidden></th></tr></thead><tbody><tr><td>Unlisted</td><td>Your game is publicly available but won't be listed on the home page. This means anyone can join through your play link or through friends.</td><td></td></tr><tr><td>Public</td><td>Your game is public and listed on the home page.</td><td></td></tr><tr><td>Private</td><td>Your game is private to your organization. Players outside of the game's organization will be unable to join.</td><td></td></tr></tbody></table>


# Game Loading Screens

You can customize what users see while your game is downloading and loading. These also show up when users transport to different servers within your game.&#x20;

The image marked default will be the image shown unless you specify a different image via TS Code.

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FfIHhXQpmlLnhAtUvgjhb%2Fimage.png?alt=media&amp;token=c96a755b-bc0d-47bc-a6b5-d90b0cc47d19" alt=""><figcaption></figcaption></figure>

Use the Image ID to set an image during server transports:

```typescript
const config: AirshipGameTransferConfig = {
    loadingScreenImageId: "123123123123",
}
Platform.Server.Transfer.TransferToServer(player, serverId, config);
```

For more information on server transfers see the [Platform Server Transfers](/platform-services/server-transfers) page


# Publish Game

{% hint style="warning" %}
Simplified publishing only works when signed in with Google. If you don't sign in with Google you can [publish using an API key](https://app.gitbook.com/o/Ob5dDteJHkKChzdNkVaS/s/IbaXflSJA8L9N9yOx089/~/changes/322/other/publishing-with-key).
{% endhint %}

### Create game

First you will need to register your game:

1. Go to [create.airship.gg](https://create.airship.gg/) and sign up with Google.
2. Click "Create" to make an organization. You can make more organizations in the future.
3. Once you have made your organization click "Create Game" and give it a name

### Publish game

Once you have created a game you can publish to it from the Unity Editor:

1. At the top of your editor click the profile picture and sign in\\

   <figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FXuZyge96vnhysB4ItAnp%2FScreenshot%202024-09-13%20at%205.21.11%20PM.png?alt=media&amp;token=c702d308-b8d7-47a5-918c-9c64279548fd" alt="" width="375"><figcaption></figcaption></figure>
2. Once you are signed in click the settings button\\

   <figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FKw59ZFxVNOEqMzi22Pa6%2FScreenshot%202024-09-13%20at%205.26.58%20PM.png?alt=media&amp;token=db3c97a9-e488-4b74-9ea4-86d6bc130e0f" alt=""><figcaption></figcaption></figure>
3. Open the Publish Target dropdown and select your game

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FbKiBzUaFw6abGkoGwf8r%2FScreenshot%202024-09-13%20at%205.31.52%20PM.png?alt=media&amp;token=eb170952-568b-4b66-84df-1940b1d73918" alt="" width="310"><figcaption></figcaption></figure>

4. Click publish at the top of your screen

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2F5Bz3PZZZ1vqbTVPY5H6n%2FScreenshot%202024-09-13%20at%205.49.13%20PM.png?alt=media&amp;token=ca6c9c1d-a321-4795-9d7b-fc074b147dc1" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
Your first publish might take a few minutes. Future publishes will be faster.
{% endhint %}

{% hint style="warning" %}
**If you see errors saying you are missing modules, you need to install Unity build modules**

1. Open Unity Hub and select the Installations tab
2. Press Manage on the installation you have been using for Airship
3. Click on Add Modules for
   * Android Build Support
   * iOS Build Support
   * Linux Build Support (IL2CPP)
   * Windows Build Support (IL2CPP)
   * Mac Build Support (Mono)
4. Install the module, restart Unity Editor, and Publish your game!
   {% endhint %}

### Play your game

Once your game is live you will see a message in your console with a link to play your game on Steam. By default your game is [unlisted](/publishing/create-dashboard-game-cms/game-visibility), meaning you can send this link to friends and play together. Congrats!

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FPFhtb7XvQFwPmaeDyPSb%2FScreenshot%202024-09-13%20at%205.56.16%20PM.png?alt=media&amp;token=f12b4413-1690-49bb-a57b-de4d0bc5d3a1" alt="" width="375"><figcaption></figcaption></figure>


# Publishing with API Key

{% hint style="info" %}
If you signed up with Google for your Airship account the steps to publish are [here](/publishing/publish-game).
{% endhint %}

If you aren't signed into editor you can still publish your game using API keys.

### Registering an API Key

1. Go to your [organization's API keys dashboard](https://create.airship.gg/dashboard/organization/api-keys) and click `Create Key` .&#x20;
2. Give your key permission to publish to the game you want to deploy to.
3. In Unity Editor go to `Airship > Configuration` and paste the key in `Airship API Key`

<div align="center" data-full-width="false"><figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FrMFUyUqVipHd90LzmC0E%2FScreenshot%202025-07-24%20at%205.50.20%20PM.png?alt=media&amp;token=4942144f-f09f-43e0-b031-3ac5846f1907" alt="" width="116"><figcaption></figcaption></figure></div>

### Setting Up Your Publish Target

1. Grab your game id from your [create dashboard](https://create.airship.gg/dashboard).

<div data-full-width="false"><figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2F8fyw2QPngeo2EV3hjqKs%2FScreenshot%202025-07-24%20at%205.45.13%20PM.png?alt=media&amp;token=f3aa0085-4c49-4dab-9dff-caa3c5e8488c" alt="" width="375"><figcaption></figcaption></figure></div>

2. Go to your game config

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FKw59ZFxVNOEqMzi22Pa6%2FScreenshot%202024-09-13%20at%205.26.58%20PM.png?alt=media&amp;token=db3c97a9-e488-4b74-9ea4-86d6bc130e0f" alt="" width="176"><figcaption></figcaption></figure>

3. Paste in your game id to `Target game id` and click `Submit`

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FpbDXxWHZVIiztzm8ngNV%2FScreenshot%202025-07-24%20at%206.01.48%20PM.png?alt=media&amp;token=9cab65c5-6451-41a2-bfb0-36b4c782cca4" alt="" width="375"><figcaption></figcaption></figure>

{% hint style="success" %}
If your game names shows up next to "Publish target" you are ready to deploy!
{% endhint %}


# What is the Core Package?

The Core Package is a collection of TypeScript and art assets that are included in every game on Airship. The Core Package is known as "@Easy/Core". Contents include API's for characters, user input, and more.&#x20;

This section of the docs includes information on the different parts of the Core Package.&#x20;


# Chat Commands

Quickly run code from the chat window

Airship has a built in command system. The API is exposed so you can register your own chat commands.

## Chat Command Structure

All commands are run with the / character followed by the command keyword, then parameters separated by spaces:

```
/mycommand 12 secondParam
```

## Example Command

```typescript
import { Airship } from "@Easy/Core/Shared/Airship";
import { ChatCommand } from "@Easy/Core/Shared/Commands/ChatCommand";
import { Player } from "@Easy/Core/Shared/Player/Player";

export class MyCommand extends ChatCommand {
	constructor() {
		// command name, alias, usage hints, and description
		super("mycommand", ["c"], "[string] (optional)", "Print a message");
	}

	// Player that sent the command and the variables passed through as string arguments
	public Execute(player: Player, args: string[]): void {

		// Get the parameter if it was sent
		let firstParameter = ""
		if(args.size() > 0){
			firstParameter = args[0];
		}
		
		// Create a log message
		const logMessage = "Client sent message: " + firstParameter;

		// Log to console on server
		print(logMessage);

		// Send the results to every clients chat window
		Airship.Chat.BroadcastMessage(logMessage);
	}
}
```

You must register the command on the server. Do this from some AirshipBehaviour that lives in your scene:

```typescript
import { Airship } from "@Easy/Core/Shared/Airship";
import { Game } from "@Easy/Core/Shared/Game";
import MyCommand from "./MyCommand";

export default class CommandManager extends AirshipBehaviour {
	override Start() {
		if (Game.IsServer()) {
			Airship.Chat.RegisterCommand(new MyCommand());
		}
	}
}
```


# Proximity Prompts

Proximity prompts are a fast way to listen for player input in world.

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FhQfpBNBwK04F5FTQmJFd%2FScreenshot%202024-09-13%20at%207.16.05%20PM.png?alt=media&amp;token=269acde0-b3fa-4616-9677-5a93f2744a93" alt="" width="235"><figcaption></figcaption></figure>

### Creating Prompts

The simplest way to create a prompt is to drag Core's ProximityPrompt prefab onto your game object.&#x20;

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2Fb6iHWK0VQV1xnSPSIATD%2FScreenshot%202024-09-13%20at%207.24.26%20PM.png?alt=media&amp;token=63e09d49-5241-4ec2-9283-9cb5fe7a19b5" alt=""><figcaption></figcaption></figure>

To listen to prompt input you can use `onActivated`:

```typescript
import ProximityPrompt from "@Easy/Core/Shared/Input/ProximityPrompts/ProximityPrompt";

export default class PromptExample extends AirshipBehaviour {
	public prompt: ProximityPrompt;
	override Start(): void {
		this.prompt.onActivated.Connect(() => {
			print("Activated prompt");
		});
	}
}

```

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FftUIbu7ciOWklyqahWWS%2FScreenshot%202024-09-13%20at%207.32.13%20PM.png?alt=media&amp;token=7a471f03-eb03-4a9d-830c-4ebc2e78dcbd" alt="" width="375"><figcaption><p>PromptExample component on Cube Game Object</p></figcaption></figure>

{% hint style="info" %}
onActivated will only ever be fired when the local client interacts with a prompt. This cannot be listened to on the server. To network the result check out [Network Signals](/networking/network-signals).
{% endhint %}

### Customization

Because a Proximity Prompt is a prefab you can entirely change how it displays.

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2F6LdFFValYRN4z896Wt5B%2FScreenshot%202024-09-13%20at%207.42.05%20PM.png?alt=media&amp;token=0b6ace87-8f2d-4b9a-8050-d2d8ef5a2ac0" alt="" width="168"><figcaption></figcaption></figure>

There are a few core customization fields on the Proximity Prompt that you can change in editor or through code:

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FLyY0OmME0Uo8cOhe50R5%2FScreenshot%202024-09-13%20at%207.47.25%20PM.png?alt=media&amp;token=758b930c-b320-45dd-85d9-b83cc6fd9c47" alt="" width="375"><figcaption></figcaption></figure>

If you're looking to change how a proximity prompt looks entirely you can modify it directly in your object. If you are wanting to repeat the same style of prompt throughout your game you'll want to set it up as a [Prefab Variant](https://docs.unity3d.com/Manual/PrefabVariants.html).

### Cross Platform

Prompts automatically work across platforms. On mobile prompts can be tapped to activate.


# Inventory

Airship has a built-in networked inventory system that is useful for quickly prototyping games.

{% hint style="info" %}
When referencing assets by path they should be under `Assets/Resources` folder (or part of a package under `Assets/AirshipPackages`). This ensures they will be included in your deploy.
{% endhint %}

```typescript
// Register a new item type
Airship.Inventory.RegisterItem("WoodSword", {
    displayName: "Wood Sword",
    accessoryPaths: ["Assets/Resources/WoodSword.prefab"],
    image: "Assets/Resources/WoodSword.png",
});
```

```typescript
// Give characters a wood sword on spawn
if (Game.IsServer()) {
    Airship.Characters.ObserveCharacters((character) => {
        character.inventory?.AddItem(new ItemStack("WoodSword"));
    });
}

```

```typescript
// Observe the local character's held item
Airship.Inventory.ObserveLocalHeldItem((itemStack) => {
    if (itemStack?.itemType === "WoodSword") {
        // start wood sword logic
    }
});
```


# VoxelWorld

VoxelWorld is our system for creating grid aligned elements. These are usually blocks like in Minecraft or Terraria but can contain special elements such as prefabs or quarterblocks.&#x20;

{% content-ref url="/spaces/IbaXflSJA8L9N9yOx089/pages/i24FFc7j086eQCyM0Vfd" %}
[Voxel World Getting Started](/core-package/voxelworld/voxel-world-getting-started)
{% endcontent-ref %}

{% content-ref url="/spaces/IbaXflSJA8L9N9yOx089/pages/czT0bARyu4A4c9zjW2P8" %}
[Voxel World Tips](/core-package/voxelworld/voxel-world-tips)
{% endcontent-ref %}

{% content-ref url="/spaces/IbaXflSJA8L9N9yOx089/pages/g8r0M96RJ3x6DzhTJjIX" %}
[Prefab Voxels](/core-package/voxelworld/prefab-voxels)
{% endcontent-ref %}

{% content-ref url="/spaces/IbaXflSJA8L9N9yOx089/pages/CPAoFMsKa7JmtOF5F2w4" %}
[QuarterBlocks](/core-package/voxelworld/quarterblocks)
{% endcontent-ref %}


# Voxel World Getting Started

How to setup a voxel world and our suggested best practices

## Creating a Voxel World

VoxelWorld is a component that you will place on a GameObject. To have a Voxel World you will need several components.

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FpZQS9psmOh5iPflpIiw1%2Fimage.png?alt=media&amp;token=ebab8d17-1fb7-4384-b123-d2b4dec68792" alt=""><figcaption></figcaption></figure>

* Voxel World - This is the main component that provides the main editor tools for creating a voxel world
* Voxel Blocks - Points to the data for your voxels
* Voxel World Networker - Handles syncing the voxels from server to clients
* Network Identity - Standard ID component for any networked object

{% hint style="info" %}
VoxelWorldNetworker and NetworkIdentity are both only needed if this is a networked voxel world. If you just want to draw something locally they are not needed.&#x20;
{% endhint %}

## Saving the Data

The world data is saved into an object in your project called a WorldSaveFile. In your VoxelWorld component you can select the save file you want, load, and save edits.&#x20;

You can create a new save file in the project by right clicking and choosing:\
`Create/Airship/VoxelWorld/VoxelWorldSaveFile`

## Drawing Blocks

To edit blocks, click the Open Editor button on the VoxelWorld component. This opens a window that you should dock somewhere convenient. The editor lets you switch between voxel worlds, select block types, and access the tools panel.

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FNVvveQMDahhxwZ3t3lL9%2Fimage.png?alt=media&amp;token=71e9b2fa-e482-46c5-9233-b37ec639df4b" alt=""><figcaption></figcaption></figure>

Tools will show up in your scene view for extra functionality

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FSemdIfSeAvqzQgVNdhZ6%2Fimage.png?alt=media&amp;token=6cc303fd-9094-4226-aca0-bee672575e89" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
Be sure to save your work after you are done editing!&#x20;
{% endhint %}


# Voxel World Tips

Below are tips for working with voxel worlds and some ideas on how to use them.

## Multiple Voxel World Instances

You can have multiple VoxelWorlds loaded, this means you can reuse stored worlds. If you have a statue that will be placed in several locations, you can make a statue save file, then create several VoxelWorld transforms that point to that file and place them around the scene. This means if you change the statue in one location it will change them for all locations, much like Unity's prefab system.

## Motion in Voxel Worlds

Since voxel worlds are tied to transforms, you can move them! If you make sure your transforms pivot point is in a meaningful location you can do fun things such as spinning a windmill or making a spaceship fly.

{% hint style="info" %}
The EasyMotion component is a quick way to add motion to your scenes.&#x20;
{% endhint %}

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2F6sm3hOU54Ek6LluAonat%2FWindmillTurn.gif?alt=media&amp;token=aa574ed5-cd55-44bc-9ee1-1f442a220ff0" alt="" width="270"><figcaption></figcaption></figure>

For this windmill a VoxelWorld save file was created for just the blades. Then the blades were placed in a parent transform that acted as the blades pivot point. With an easy motion component set to rotate, the windmill comes alive!&#x20;

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FSXrCx3HM0jdWDoXeZA7l%2Fimage.png?alt=media&amp;token=62cb97e5-598e-412b-82ef-4a1f643f785f" alt=""><figcaption></figcaption></figure>


# Prefab Voxels

`//TODO`


# QuarterBlocks

Quarterblocks are a feature of VoxelWorld that allows you to have "beveled blocks".

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2F4m7Bt9lTZoNqq2coVl0M%2Fimage.png?alt=media&amp;token=9100be22-5fd3-481a-8a7d-8c4c6e8af71a" alt=""><figcaption><p>Quarterblocks in action - two tilesets are visible here: A fluffy bevel for the trees and a chiseled bevel for the stonework</p></figcaption></figure>

Quarterblocks works by supplying a bunch of carefully crafted meshes that define "one quarter" of the whole block, so that all of the combinations of whole blocks can be constructed automatically based upon the neighboring conditions.

\
The minimum set of meshes you need to produce is as follows:

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FTKoUQ1ie3WvcxojhvpeF%2Fimage.png?alt=media&amp;token=89c6baad-b0fe-4c81-88ed-6f9ff509ed8b" alt=""><figcaption><p>The minimum set of blocks required to make a quarterblock set</p></figcaption></figure>

### Minimum Quarterblock tileset names

UA - Upper Front Face A

UC - Upper Top Face

UD - Upper Vertical Edge A

UE - Upper Horizontal Edge A

UG - Upper Corner A

UH - Upper Top Inner Corner A

UI - Upper Front inner Corner A

UK - Upper Inner 3-Way Corner Patch

UL - Upper Vertical Edge A with Cap\*\*

UM - Upper Horizontal Edge A with Cap\*\*

\*\* Might be going away/replaced with something easier<br>

### Pivot Points

The pivot points of these pieces is **\*ESSENTIAL\***.  All blocks are 1x1x1, with their pivot points in the center of the local 1x1x1 space. <br>

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FUfSVf7JzSTQdc96dl17Q%2Fimage.png?alt=media&amp;token=b9f9182e-fe42-48e2-ac37-c8eaa3fc149e" alt=""><figcaption><p>All pivot points must be in the center of the 1x1x1 block they're a part of</p></figcaption></figure>

###

### Missing blocks

You can actually define a lot more than this, but if you don't explicitly define these next set, the engine will synthesize  them from existing blocks by mirroring or flipping them.

### "U" faces

All of the minimum set is the U faces, the "Upper" half of one block.

### "D" faces&#x20;

D faces are the are the lower faces, the "Down" half of one block. If these are not present in the source meshes, they'll be generated automatically by flipping the matching "U" face.

### "B" faces&#x20;

B faces are the horizontally flipped versions of faces.  eg: Top Right corner is the A face, Top Left corner is the B face. If these are not present in the source meshes, they'll be generated automatically by flipping the matching "A" face.

## Creating a Set

1\) Export your mesh to Unity to a folder inside of ![](https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2Ft6ZBson4kAIYnrg8pFXs%2Fimage.png?alt=media\&token=daeb3c5e-41f2-4865-b1a5-096286a32a21)

2\) Rightclick the mesh and use "Split Model Into Prefabs"\
![](https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2F3PR8migeDKvs2wjyhwbk%2Fimage.png?alt=media\&token=fa7d02ef-526e-4412-a6b4-1b0c624eceba)

* If there is a material the same name as the mesh, this material will be applied to all of the parts automatically!
* If any of the mesh parts start with "\_" they will be skipped.
* **Make sure to set the imported scale to 1 inside unity with Convert Units unchecked!**\
  ![](https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FGFFUfHr28nwaHxVpKb66%2Fimage.png?alt=media\&token=0489399e-732c-40ef-98d2-c833fbabf34d)

## Using a set:

In the blockdefines.XML, specify \<TileSet> like so\
![](https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2Fnien9yPnt8vCj68utFO8%2Fimage.png?alt=media\&token=671abf16-a7df-4d50-95bf-a14daf393e8a)

* You will want to set **\<Solid>false\</Solid>**, so the engine knows there are air gaps in this tileset
* You will want to set **\<Collision>Solid\</Collision>,** so players will correctly collide
* You can use \<Material> to override the material in the prefabs

## To test

Reload Voxelworld in the VoxelWorld scene via the "Load World" button

## Appendix A - Full list

UA - Upper Front Face A

DA - Lower Front Face A

UB - Upper Front Face B

DB - Lower Front Face B

UC - Upper Top Face&#x20;

DC - Lower Bottom Face

UD - Upper Vertical Edge A

DD - Lower Vertical Edge A

UE - Upper Horizontal Edge A\
DE - Lower Horizontal Edge A

UF - Upper Horizontal Edge B\
DF - Lower Horizontal Edge B

UG - Upper Corner A\
DG - Lower Corner A<br>

UH - Upper Top Inner Corner A

DH - Lower Bottom Inner Corner A

UI - Upper Front Inner Corner A

DI - Lower Front Inner Corner A

UK - Upper Inner 3-Way Corner Patch

DK - Lower Inner 3-Way Corner Patch

UL - Upper Vertical Edge A with Cap\*\*

DL - Lower Vertical Edge A with Cap\*\*

\
UM - Upper Horizontal Edge A with Cap\*\*

DM  - Lower Horizontal Edge A with Cap\*\*

UN - Upper Horizontal Edge B with Cap\*\*

DN  - Lower Horizontal Edge B with Cap\*\*


# Enable / Disable Core Features

To easily configure your project you can add the CharacterConfigSetup component to any game object in your scene.

* Click on your game object
* Add Component: "Script Binding"
* Click "Add Airship Component"
* Search and select "CharacterConfigSetup"

You now can control many of the core systems. These toggles will fire as soon as your scene is loaded.&#x20;

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FisUyZWU3HDAppaH8L5Jz%2Fimage.png?alt=media&amp;token=e7ff2deb-2215-4f97-bbe5-0e9ba3490c4a" alt="" width="367"><figcaption></figcaption></figure>

If you need to control these options dynamically, they are all accessible via TS

```typescript
public OnEnable() {
	//Character
	//Set the default prefab to use whenever a character is spawned
	Airship.characters.SetDefaultCharacterPrefab(this.customCharacterPrefab);

	//Local Character Configs
	if (Game.IsClient()) {
		//Movement
		//Control how client inputs are recieved by the movement system
		Airship.characters.localCharacterManager.SetMoveDirWorldSpace(this.movementSpace === Space.World);

		//Camera
		//Toggle the core camera system
		Airship.characterCamera.SetEnabled(this.useAirshipCameraSystem);
		if (this.useAirshipCameraSystem) {
			//Allow clients to toggle their view model
			Airship.characterCamera.canToggleFirstPerson = this.allowFirstPersonToggle;
			if (this.startInFirstPerson) {
				//Change to a new camera mode
				Airship.characterCamera.SetCharacterCameraMode(CharacterCameraMode.Locked);
				//Force first person view model
				Airship.characterCamera.SetFirstPerson(this.startInFirstPerson);
			}
		}

		//UI visual toggles
		Airship.chat.SetUIEnabled(this.showChat);
		Airship.inventory.SetBackpackVisible(this.showInventoryBackpack);
		if (this.showInventoryHotbar || this.showHealthbar) {
			Airship.inventory.SetUIEnabled(true);
			Airship.inventory.SetHealtbarVisible(this.showHealthbar);
			Airship.inventory.SetHotbarVisible(this.showInventoryHotbar);
		} else {
			Airship.inventory.SetUIEnabled(false);
		}
	}

	//Stop any input for some movement options we don't use
	if (!this.enableJumping || !this.enableCrouching || !this.enableSprinting) {
		//Listen to input event
		Airship.characters.localCharacterManager.onBeforeLocalEntityInput.Connect((event) => {
			//Force the event off if we don't want that feature
			if (!this.enableJumping) {
				event.jump = false;
			}
			if (!this.enableCrouching) {
				event.crouchOrSlide = false;
			}
			if (!this.enableSprinting) {
				event.sprinting = false;
			}
		});
	}
}
```


# Developer Console

While on steam, you can press `[F1]` to open the Developer Console. This lets you view client and server logs.&#x20;

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FjHTJayq8LIQqZ4ePEV1D%2FScreenshot%202024-09-06%20at%2011.37.21%E2%80%AFAM.png?alt=media&amp;token=e8194f04-52d1-45cf-99f5-2849ad3d5f99" alt=""><figcaption></figcaption></figure>


# Data Store

The Data Store provides simple key/value persistent storage. The Data Store API can be accessed using `Platform.Server.DataStore`.

* Data Store is durable. Data saved will not be deleted or cleaned up.
* The Data Store API can only be used on the server.
* Data Store is slower than Cache Store.

Some common use cases for the Data Store are:

* User Profiles
* Tracking Unlocks
* Persistent Inventory

{% hint style="info" %}
Data Store is intended to be used for general purpose persistent key/value storage. Check out [Cache Store](/platform-services/cache-store), [Leaderboards](/platform-services/leaderboards), and [Platform Inventory](/platform-services/platform-inventory) for more specialized data storage situations.
{% endhint %}

{% hint style="info" %}
Data store keys must be alphanumeric and only contain allowed symbols: -, ., \_, :
{% endhint %}

## Common Patterns

```typescript
// Store user unlocks
const unlocks: UnlockData = {
    level1: true,
    level2: true,
    level3: false,
}
await Platform.Server.DataStore.SetKey(`Unlocks:${player.userId}`, unlocks);

// Get user unlocks
const result = await Platform.Server.DataStore.GetKey<UnlockData>(
    `Unlocks:${player.userId}`,
);
if (!result) return; // Key did not exist

// Check if user has unlocked level2
if (result.level2) {
    // Unlocked!
}
```


# Locking

Data Store keys can be locked to a specific game server by calling `LockKeyOrStealSafely()` or `LockKey()`. Keys can be locked in two modes:

| Mode        | Description                                                                   |
| ----------- | ----------------------------------------------------------------------------- |
| `ReadWrite` | Blocks reads and writes on all other servers. This is the default.            |
| `Write`     | Blocks writes on all other servers. All servers can read the key at any time. |

A key lock will last for 24 hours, or until it is unlocked with the `UnlockKey()` function. Normally, only the server that owns the lock can unlock the key. However, other servers can steal a lock by passing the serverId that owns the lock to the `LockKey()` or `UnlockKey()` functions. This should only be done in cases where you know the lock can be stolen safely (ex. the server that owns the lock is offline). You can retrieve the current owner of a lock, along with additional lock data using `GetLockDataForKey()`.&#x20;

## Locking Patterns

For simple lock cases, it is best to use the `LockKeyOrStealSafely()` function:

```typescript
Airship.Players.onPlayerJoined.Connect(async (player) => {
	const result = await Platform.Server.DataStore.LockKeyOrStealSafely(
		`progress:${player.userId}`
	);
	if (!result) player.Kick("Unable to load progress.");
	
	// You can now safely read and write to this key. No other server
	// can read or modify it.
	this.progress[player.userId] = await Platform.Server.DataStore.GetKey(
		`progress:${player.userId}`
	);
});

Airship.Players.onPlayerDisconnected.Connect(async (player) => {
	await Platform.Server.DataStore.SetKey(
		`progress:${player.userId}`,
		this.progress[player.userId],
	);
	delete this.progress[player.userId];
	// Release the key when the player disconnects.
	await Platform.Server.DataStore.UnlockKey(`progress:${player.userId}`);
});

Platform.Server.Transfer.onShutdown.Connect(() => {
	Promise.allSettled(ObjectUtils.keys(this.progress).map(async userId => {
		await Platform.Server.DataStore.SetKey(
			`progress:${player.userId}`,
			this.progress[player.userId],
		);
		await Platform.Server.DataStore.UnlockKey(
			`progress:${player.userId}`
		);
	})).expect();
});
```


# Cache Store

The Cache Store provides simple key/value cache storage. The Cache Store API can be accessed using `Platform.Server.CacheStore`.

* Cache Store is not durable. Data will be cleaned up if not used.
* The Cache Store API can only be used on the server.
* Cache Store is faster than Data Store.

Some common use cases for Cache Store are:

* Temporary Cooldowns on accessing content
* Share Codes for joining a match

{% hint style="info" %}
Cache Store is intended to be used for short-lived, non-durable key/value storage. If you need persistent storage without expiration times, checkout [Data Store](/platform-services/data-store).
{% endhint %}

## Common Patterns

```typescript
// Create a queue cooldown
await Platform.Server.CacheStore.SetKey(
    `BossQueue:${player.userId}`, // The key for this cache entry
    os.time(), // The time the cooldown was created is stored as the value
    60, // 60 second cooldown
);

// Check a queue cooldown
const result = await Platform.server.cacheStore.GetKey<number>(`BossQueue:${player.userId}`);
if (result) {
    // On cooldown
} else {
    // Not on cooldown
}
```


# Leaderboards

The Leaderboard API can be accessed using `Platform.Server.Leaderboard`.

* Leaderboards are durable. Data will not be cleaned up or deleted.
* The Leaderboard API can only be used on the server.
* Overall leaderboard rankings retrieved from GetRankRange() will reflect changes immediately.
* Placement for individual entries retrieved from GetRank() may take up to 1 minute to reflect changes.

Leaderboards must be created on the create dashboard before use:

<https://create.airship.gg/dashboard/organization/game/leaderboards>

## Leaderboard Keys

If you are tracking player stats with leaderboards, it's often best to use the player's userId as the key. Though the most common keys are user IDs, you can use any unique value as a leaderboard key. For example, if you have a clan system in your game, you could use the clan ID to track total wins for a given clan.

## Common Patterns

```typescript
// Update a leaderboard
await Platform.Server.Leaderboard.Update("TopScores", {
    [player1.userId]: 123,
    [player2.userId]: 234,
})
```

```typescript
// Get top scores for a leaderboard in realtime
// Contains an array of objects with the id, rank, and value
const entries = await Platform.Server.Leaderboard.GetRankRange("TopScores");

// Get the usernames to display
const idMap = await Platform.Server.User.GetUsersById(entries.map(e => e.id));

// Array of objects containing userData, rank, and scoreValue.
const entriesWithUserdata = entries.map((entry) => {
    return {
        username: idMap[entry.id]?.username ?? "Unknown User",
        rank: entry.rank,
        scoreValue: entry.value,
    }
});
```

```typescript
// Get the rank of a given id (note: results may be delayed up to 1 minute)
const result = await Platform.Server.Leaderboard.GetRank("TopScores", player.userId);
if (!result) return; // No entry for this userId

// Result is an object with the fields id, rank, and value
const rank = result.rank;
```


# Platform Inventory

Platform Inventory is an inventory system much like the Steam Inventory system. Items in this inventory are accessible outside of your game, and in the future will be tradable and marketable. Platform inventory can be accessed using `Platform.Client.Inventory` on the client and `Platform.Server.Inventory` on the server.

* Platform inventory is persistent and will not be cleaned up or deleted.
* Items in this inventory do not stack. Each item has it's own unique instance ID.
* Games can only access and manage items created by their game or organization.

Platform Inventory items are instances of item classes that are defined in the create dashboard. You can create item classes for a game or for an organization. You must create an item class before you can create an item instance.

* <https://create.airship.gg/dashboard/organization/game/items>
* <https://create.airship.gg/dashboard/organization/items>

{% hint style="warning" %}
Platform Inventory is intended to be used for things like collectibles and purchasable items. It has strong integrations with real currency transactions as well as audit logging and should be used for things that players may want to buy, sell or trade. If you want to build a general purpose persistent inventory, check out [Data Store](/platform-services/data-store).
{% endhint %}

## Item Floats

Each instance of an item that is created has a randomly generated float value associated with it. This float will be greater than or equal to 0 and less than 1. Floats are generated with a uniform distribution, meaning you are equally likely to get a value of 0 as you are a value of 0.5 or 0.9.

### Common Uses for Floats

Since float values are attached to the item instance and do not change when the item is traded or sold, floats can be a good way to create unique qualities for an item. For example, if you wanted to have a weapon that had a 0.1% chance of being gold, you could render the weapon as a gold variant if the user's item instance has a float value of less than 0.001.


# Server Management

Airship provides tools for creating and managing instances of game servers through the `Platform.Server.ServerManager` API.

## Creating Servers

You can create a server by calling `CreateServer()`. You can provide additional parameters to this function to define things like the starting scene, the access mode, and other custom configuration.

{% hint style="info" %}
More information on creating servers is available on the [Server Transfers](/platform-services/server-transfers) page.
{% endhint %}

## Shutting Down Servers

Game servers with no players are automatically shut down after a few minutes, so you don't need to explicitly shut down a game server. If you do want to shut down a game server, you can use the `ShutdownServer()` function.

## Retrieving Server Data

You can retrieve basic server configuration information for any running game server using the `GetServer()` function.


# Server List

Airship provides a basic server list that can be used to retrieve servers which may be accessible to a player in your game. The server list functions can be found in `Platform.Server.ServerManager`.

## Listing a Server

A server can be listed at any time using the following code:

```typescript
await Platform.Server.ServerManager.ListServer({
    // Name and description are optional
    name: "My Server",
    description: "A running server you can join",
})
```

You can call this again to update the name or description.

## Delist a Server

If you want to remove a server from the list, you can do so at any time using the following code:

```typescript
await Platform.Server.ServerManager.DelistServer();
```

Calling this function multiple times will have no effect.

## Retrieving the Server List

The server list for a game can be retrieved on both the client and server side. Both the client and server have access to the full list using `GetServerList()`. This function returns the most populated servers first.

Additionally, the client has access to `GetFriendServers()` which returns any listed servers their friends are playing on.

## Common Patterns

### Create a Match with a Lobby Only Friends Can Join

```typescript
// When the player clicks "create a lobby", create a server for them and move them
// to it.
const server = await Platform.ServerManager.CreateServer({
    sceneId: "LobbyScene",
    accessMode: AccessMode.FriendsOnly,
});
// We use "TransferToMatchingServer" to bypass the access rules for the owner. We
// won't do this for other players since we want to perform access checks for them.
await Platform.Server.Transfer.TransferToMatchingServer(player, {
    serverId: server.serverId,
});
```

```typescript
// In our lobby scene on the new server, we can list the server when a player joins
const cleanUpConnection = Airship.Players.onPlayerJoined.Connect(async (player) => {
    // The first player to connect is the owner of the lobby
    owner = player;
    // Clean up the connection so we don't overwrite the owner when another
    // player joins
    cleanUpConnection();
    
    // List the server for the owner's friends to find
    await Platform.Server.ServerManager.ListServer({
        name: `${owner.username}'s Server`
    })
})

// We can also unlist the server when the owner starts the match
YourGameManager.onStartMatch.Connect(async () => {
    await Platform.Server.ServerManager.UnlistServer();
})
```

```typescript
// Clients can retrieve servers their friends are on
const servers = await Platform.Client.ServerList.GetFriendServers();

// When they select their friend's lobby in a UI, send a network request to the
// server they are connected to requesting to transfer. (You'll have to set this up,
// see our docs on Network Functions)
Network.JoinLobby.client.FireServer(server.serverId);
```

```typescript
// On the friends server, we get the client event and process it
Network.JoinLobby.server.OnClientEvent((player, serverId) => {
    // We can get the requested server's data to do additional checks
    // if we want to.
    const serverData = await Platform.Server.ServerManager.GetServer(serverId);
    if (!serverData || serverData.sceneId !== "LobbyScene") return;
    
    // Send the friend to the new lobby server
    await Platform.Server.Transfer.TransferToServer(friend, serverId);
})
```


# Server Transfers

The transfer APIs allow you to move players between servers. You can access server transfer functions using `Platform.Server.Transfer`.

```typescript
// Allocate a new server. The default acess mode is Closed. This server
// will only be accessible to players moved via server side transfer requests.
const server = await Platform.Server.ServerManager.CreateServer({
    sceneId: "CustomScene",
});
// Move players to the new server.
await Platform.Server.Transfer.TransferGroupToServer(players, server.serverId);
```

## Transfer Functions

### Transfer to Game

Transfers a group of players to the given game, additionally you can provide a preferred server ID. This preferred server ID can be on any scene. Access checks will be applied for all players. If any players cannot be transferred to the preferred server, a default server will be found or created and all players will be transferred there.&#x20;

{% hint style="info" %}
See the [#access-modes](#access-modes "mention") section for more information on how server access is decided.
{% endhint %}

### Transfer to Matching Server

This function uses the parameters you provide to find a game server for a group of players. This function does *not* check that players are allowed to access the matching server. If you want to use access checks, use the "TransferToServer" function.

This function is useful for cases where you already know access is allowed, or you explicitly want to ignore access rules.

### Transfer to Server

This function allows you to transfer a group of players to a specific server ID. If any players are unable to access the provided server ID, the function will fail. If you want to ignore access checks, use the "TransferToMatchingServer" function instead.

### Transfer to Player

Transfers a group of players to a target player. If any of the players are unable to access the server the target player is on, the players without access will be left behind and remain in their current server.

### Common Behaviors

There are a few common behaviors for all transfer functions:

* A player can only be transferred by a game server if the player is currently playing that game.
* Any game server can transfer any player playing the game.
* Transfers are not guaranteed. It is possible for the client to cancel or ignore the transfer request. The success value returned by the API only indicates that the transfer request was submitted, not that the transfer has occurred.
* Generally transfers happen almost instantly, but it is possible for a transfer to occur after a few minutes depending on server availability and startup time.

## Starting Scenes

When a server is created, a starting scene is provided to the server. This starting scene is recorded for the lifetime of the server, and is used when deciding how to route players to a server. If the server changes its scene while running, server selection and transfer behavior will not be affected and the starting scene will continue to be used.

{% hint style="info" %}
To change the default starting scene, you can modify  "Starting Scene" in the `GameConfig` asset.
{% endhint %}

<table><thead><tr><th width="315">Transfer Function</th><th>Scene Awareness</th></tr></thead><tbody><tr><td><code>TransferToServer()</code> </td><td>Ignores the server starting scene entirely. Players are always moved to the server if access is allowed.</td></tr><tr><td><code>TransferToGame()</code> </td><td>Will first attempt to transfer the players to the preferred server first, this attempt does <em>not</em> check the starting scene. If the preferred server cannot be joined, a server on the default scene is found or created instead.</td></tr><tr><td><code>TransferToMatchingServer()</code></td><td>Matches the starting scene provided in the configuration parameters. If no sceneId is provided, any scene will be accepted.</td></tr><tr><td><code>TransferToPlayer()</code></td><td>Ignores the server starting scene entirely. Players are always moved to the server if access is allowed.</td></tr></tbody></table>

## Access Modes

All game servers are assigned an access mode when they are created. Access modes control which players can join a given game server and the methods by which they can join the server. Default servers a client joins through the main menu will always have the "Open" access mode. You can create servers with different access modes using the `CreateServer` function.

{% hint style="info" %}
Access Mode can be changed at runtime using the Server Manager API: `Platform.Server.ServerManager.SetAccessMode();`
{% endhint %}

<table><thead><tr><th width="198">Access Mode</th><th>Description</th></tr></thead><tbody><tr><td>Open</td><td>Any player is allowed to join the server.</td></tr><tr><td>Closed</td><td>Clients cannot join the server through their friends list or client side transfer requests. Players can only join if a game server requests the transfer. This is the default mode for new servers created with <code>CreateServer()</code></td></tr><tr><td>Friends Only</td><td>Only users that have friends on the server can join. Server side transfer requests will also respect this mode. This means that the first player to join the server must be transferred using TransferToMatchingServer (see examples below).</td></tr></tbody></table>

## Transfer Data

When transferring a player or group of players, you can optionally specify a few configuration fields:

<table><thead><tr><th width="263">Field</th><th>Description</th></tr></thead><tbody><tr><td><code>clientTransferData</code></td><td>An object that will be passed to the client. This is also visible to the server they join.</td></tr><tr><td><code>serverTransferData</code></td><td>An object that will be passed to the game server when the client joins. This is not visible to the client.</td></tr><tr><td><code>loadingScreenImageId</code></td><td>The ID of the image to display on the loading screen for this transfer. You can upload loading screen images on the<a href="https://create.airship.gg/dashboard/organization/game/settings"> Airship Create</a> site.</td></tr></tbody></table>

## Common Patterns

### Transfer Players to Default Servers

```typescript
// Transfer players back to your game's lobby (Default servers)
await Platform.Server.Transfer.TransferGroupToGame(players, Game.gameId);
```

### Create a Match Server Anyone Can Join

```typescript
// Create an open match server. Anyone can join these servers at any time.
let server = await Platform.Server.ServerManager.CreateServer({
    accessMode: AirshipServerAccessMode.Open, // The default mode is Closed
    sceneId: "MatchScene",
});
await Platform.Server.Transfer.TransferGroupToServer(players, server.serverId);
```

```typescript
// Backfill a group to an open match server in their region.
await Platform.Server.Transfer.TransferGroupToMatchingServer(players, {
    sceneId: "MatchScene",
    accessMode: AirshipServerAccessMode.Open,
});
```

### Find or Create a Server

```typescript
// Find a server for the group. Make sure we check that the access mode is set to
// "Open" so we don't accidently join a private match.
const result = await Platform.Server.Transfer.TransferGroupToMatchingServer(players, {
    sceneId: "MatchScene",
    accessMode: AirshipServerAccessMode.Open,
})
// "transfersRequested" being true means the group found a server, so we are done.
if (result.transfersRequested) return;

// Create a new server for the group and transfer them to it.
const server = await Platform.Server.ServerManager.CreateServer({
    sceneId: "MatchScene",
    // Access mode is Closed by default, so we set it to open explicitly
    accessMode: AirshipServerAccessMode.Open,
});
await Platform.Server.Transfer.TransferGroupToServer(players, server.serverId);
```

### Create a Private Match

```typescript
// Create a private match server for a group
const server = await Platform.Server.ServerManager.CreateServer({
    sceneId: "MatchScene",
    // We can use any access mode in combination with allowedPlayers. Players must
    // pass the checks for both access mode and be on the allowed players list
    // to join the server.
    accessMode: AirshipServerAccessMode.Closed,
    allowedPlayers: players,
});
await Platform.Server.Transfer.TransferGroupToServer(players, server.serverId);
```

### Transfer to Another Player

```typescript
// Transfer a group to a player in another server.
const result = await Platform.Server.Transfer.TransferGroupToPlayer(
    players,
    targetUserId
);

// We can check the result to see which players were transferred
if (result.transfersRequested) {
    print("These users were transferred:", inspect(result.userIds));
}
```

### Create a Friends Only Match

```typescript
// Create a server that only friends can join
const server = await Platform.Server.ServerManager.CreateServer({
    sceneId: "MatchScane",
    accessMode: AirshipServerAccessMode.FriendsOnly
});

// Transfer the owner of the match using TranferToMatchingServer
await Platform.Server.Transfer.TransferToMatchingServer(player, {
    serverId: server.serverId,
});
```

```typescript
// Other players can join using any of these methods:
await Platform.Server.Transfer.TransferToGame(otherPlayer, Game.gameId, serverId);
await Platform.Server.Transfer.TransferToPlayer(otherPlayer, friendUserId);
await Platform.Server.Transfer.TransferToServer(otherPlayer, serverId);

// You could also send anyone to the server using the TransferToMatchingServer
// function. Keep in mind, this does not perform any access checks.
await Platform.Server.Transfer.TransferToMatchingServer(otherPlayer, {
    serverId: server.serverId
})
```


# Server Messaging

Game servers can communicate with each other using the built-in Server Messaging service. This provides publish/subscribe functionality for sending messages between different game servers in real-time.

## Overview

```typescript
// Server Messaging can only be used on game servers. Calls made on the client will fail.
if (!Game.IsServer()) return;

// Subscribe to a topic to receive messages
const subscription = Platform.Server.Messaging.Subscribe("player-events", (data) => {
    print("Received message:", data);
});

// Publish a message to all subscribers of a topic
Platform.Server.Messaging.Publish("player-events", {
    event: "player-joined",
    userId: "12345",
    serverName: "Battle Arena 1"
}).then((result) => {
    if (result.success) {
        print("Message published successfully");
    }
});

// Unsubscribe when no longer needed
subscription.unsubscribe();

// Alternatively, if you are using a Bin to manage resources,
// the subscription can be added directly to it.
// this.bin.Add(subscription);
```

## Use Cases

Server Messaging is useful for coordinating game state and events across multiple servers:

* **Cross-Server Events** - Notify all servers when a global event occurs (e.g., world boss spawned)
* **Player Tracking** - Share player status updates across servers
* **Global Announcements** - Send announcements that should appear on all servers

## API Reference

### Subscribe

Subscribes to a topic, allowing you to receive messages published to that topic.

```typescript
Platform.Server.Messaging.Subscribe<T>(topic: string, callback: (data: T) => void): { unsubscribe: () => void }
```

**Parameters:**

* `topic` - The topic name to subscribe to (alphanumeric characters, underscores, and hyphens only)
* `callback` - Function called when a message is received on the subscribed topic

**Returns:**

* An object with an `unsubscribe` function to stop receiving messages. This object can also be passed to a `Bin` for automatic cleanup.

### Publish

Publishes data to a topic, allowing other subscribers to receive the message.

```typescript
Platform.Server.Messaging.Publish(topic: string, data: unknown): Promise<{ success: boolean }>
```

**Parameters:**

* `topic` - The topic name to publish to (alphanumeric characters, underscores, and hyphens only)
* `data` - The data to be sent (will be JSON serialized)

**Returns:**

* A Promise that resolves to an object with a `success` boolean, set to true if publishing was successful, false if not. You can retry failed messages later or drop them

{% hint style="info" %}
Server Messaging is designed for real-time communication between servers. Sometimes messages may not be delivered, for example if there are network issues . Always check the `success` flag when publishing messages and handle failures appropriately.
{% endhint %}

## Topic Names

Topic names must follow these rules:

* Only alphanumeric characters, underscores (`_`), and hyphens (`-`) are allowed
* Topic names are case-sensitive
* Examples: `player-events`, `global_announcements`, `server123_status`

## Common Patterns

### Global Event Broadcasting

```typescript
// Broadcast a global event to all servers
interface WorldBossSpawnedEvent {
    type: "world-boss-spawned";
    location: string;
    timestamp: number;
}

interface ServerMaintenanceEvent {
    type: "server-maintenance";
    broadcastMessage: string;
}

type GlobalEvent = WorldBossSpawnedEvent | ServerMaintenanceEvent;

export class GlobalEventManager extends AirshipBehaviour {
    private bin = new Bin();

    override Start(): void {
        if (!Game.IsServer()) return;

        // Subscribe to global events
        this.bin.Add(Platform.Server.Messaging.Subscribe("global-events", (event: GlobalEvent) => {
            this.HandleGlobalEvent(event);
        }));
    }

    override OnDestroy(): void {
        this.bin.Clean();
    }

    private HandleGlobalEvent(event: GlobalEvent): void {
        switch (event.type) {
            case "world-boss-spawned":
                this.ShowWorldBossNotification(event.location);
                break;
            case "server-maintenance":
                this.ShowMaintenanceWarning(event.broadcastMessage);
                break;
        }
    }

    public BroadcastWorldBoss(location: string): void {
        Platform.Server.Messaging.Publish("global-events", {
            type: "world-boss-spawned",
            location: location,
            timestamp: os.time()
        });
    }
}
```

### Cross-Server Player Tracking

```typescript
// Track player status across servers
interface PlayerStatusUpdate {
    userId: string;
    action: "joined" | "left";
    serverId: string;
    timestamp: number;
}

export class PlayerTracker extends AirshipBehaviour {
    private playerSubscription: { unsubscribe: () => void } | undefined;
    private playerJoinedConnection: { disconnect: () => void } | undefined;
    
    override Start(): void {
        if (!Game.IsServer()) return;
        
        // Subscribe to player status updates
        this.playerSubscription = Platform.Server.Messaging.Subscribe<PlayerStatusUpdate>("player-status", (update) => {
            this.UpdatePlayerStatus(update);
        });
        
        // Notify when players join this server
        this.playerJoinedConnection = Airship.Players.onPlayerJoined.Connect((player) => {
            Platform.Server.Messaging.Publish("player-status", {
                userId: player.userId,
                action: "joined",
                serverId: Game.serverId,
                timestamp: os.time()
            } as PlayerStatusUpdate);
        });
    }
    
    private UpdatePlayerStatus(update: PlayerStatusUpdate): void {
        // Update friend lists, player counts, etc.
        print(`Player ${update.userId} ${update.action} server ${update.serverId}`);
    }
    
    override OnDestroy(): void {
        // Clean up subscription and connection
        this.playerSubscription?.unsubscribe();
        this.playerJoinedConnection?.disconnect();
    }
}
```

### Periodic Status Updates

```typescript
// Send periodic server status updates
interface ServerStatusUpdate {
    serverId: string;
    playerCount: number;
    uptime: number;
}

export class ServerStatusReporter extends AirshipBehaviour {
    override Start(): void {
        if (!Game.IsServer()) return;

        // Send status update every 30 seconds
        SetInterval(30, () => {
            Platform.Server.Messaging.Publish("server-status", {
                serverId: Game.serverId,
                playerCount: Airship.Players.GetPlayers().size(),
                uptime: Time.time,
            } as ServerStatusUpdate);
        });
    }
}
```

## Best Practices

* **Unsubscribe when done** - Always use a `Bin` or call `unsubscribe()` when you no longer need to receive messages to prevent memory leaks.
* **Use descriptive topic names** - Choose clear, consistent naming conventions for your topics
* **Handle errors gracefully** - Check the `success` flag when publishing and handle failures appropriately
* **Keep messages small** - Avoid sending large data objects; consider using references to shared data stored in the [Data Store](/platform-services/data-store) or [Cache Store](/platform-services/cache-store)
* **Avoid message loops** - Be careful not to create infinite loops where servers keep responding to each other's messages

## Limitations

* Messages are not guaranteed to be delivered (fire-and-forget)
* No message ordering guarantees between different topics
* Topic names are limited to alphanumeric characters, underscores, and hyphens
* Messages are JSON serialized, so complex objects may lose information
* Server Messaging is only available on game servers, not on clients


# Users

User information such as friends and profile data are made available to both the server and client. You can access the User API using `Platform.Server.User` and `Platform.Client.User`.

## Common Patterns

```typescript
// Get a users friends
// List of objects containing user data such as username and status text.
const friends = await Platform.client.user.GetFriends();
```


# Parties

The Party API provides a single, platform level party system. Players can stay in the same party even if they are not in the same server or the same game. You can access party information using `Platform.Server.Party` and `Platform.Client.Party`. You can invite or remove players from a party in `Platform.Client.Party`.

* Players are always in a party when online. By default, a player will be in a party by themselves.
* A player's party can change at any time.

{% hint style="info" %}
If you're looking to create your own party or group system in a game, checkout [Matchmaking Groups](/platform-services/matchmaking#groups). Matchmaking groups gives your game full control over how players are grouped and can be used even if you don't need matchmaking services.
{% endhint %}

## Common Patterns

```typescript
// Get a user's party
const party = await Platform.party.GetPartyForUserId(player.userId);
if (!party) return; // No party. The user may have no party if they are offline.

// Party data such as members and leader
const members = party.members;
```


# Matchmaking

Matchmaking Platform Documentation

## Overview

The Airship platform provides a robust Matchmaking system for game developers to quickly implement competitive, multiplayer gaming. With minimal configuration, you can easily setup skill based, role based, and other types of matchmaking queues that easily integrate into your existing Airship games.

## Quickstart

**More documentation is below**, this exists to help you quickly get familiar with the core concepts of matchmaking.

After creating a matchmaking queue in the Create Airship console:

```typescript
// Server
// Create a matchmaking group with various users
const createGroupResult = await Platform.Server.Matchmaking.CreateGroup(
    userIds,
);
const groupId = createGroupResult.groupId;
```

```typescript
// Join a preconfigured matchmaking queue
// This begins the matchmaking process for this group
// Configure your matchmaking queue's on create.airship.gg
await Platform.Server.Matchmaking.JoinQueue({
    groupId: groupId,
    queueId: "team-deathmatch", 
});
```

```typescript
// Leave a matchmaking queue
await Platform.Server.Matchmaking.LeaveQueue(this.matchmakerSingleton.groupId);
```

```typescript
// Leave the matchmaking process on a game client, setting the matchmaking group
// to IDLE.
// Note: The user will still be a part of the group and the entire group will leave
// the queue.
// To start matchmaking again, the server will need to call
// `Platform.Server.Matchmaking.JoinQueue`
const result = await Platform.Client.Matchmaking.LeaveQueue();
```

```typescript
// Get information about groups and their status

// Server

// Get matchmaking group + status
const group = await Platform.Server.Matchmaking.GetGroupById(
    this.matchmakerSingleton.groupId,
);

// Get the matchmaking group + status for a specific user
// This is useful if you don't have the group id, check if they are in a group
const group = await Platform.Server.Matchmaking.GetGroupByUserId(
    player.userId,
);

// On a server that was started by the matchmaking service, you can get
// the match configuration, which includes the teams, groups, players, and
// attributes for the match.
const matchConfig = await Platform.Server.Matchmaking.GetMatchConfig();

// Client

// On the player, check to see if the player is a part of a matchmaking group
const group = await Platform.Client.Matchmaking.GetCurrentGroup();

// Run code when the local player's group changes. 
Platform.Client.Matchmaking.onGroupChange.Connect((group) => {
    // This code runs when the local players group changes.
    // The "group" parameter will contain the new group data.
    print(group.status);
})
```

## Concepts

Group - A collection of players who should get put into matches together. This can be a party, a single player, or any collection of Airship Users.

Queue - Where groups get matched together. A queue has a configuration consisting of teams & rules that designate how players should be matched together.

Team - A set of Groups that are a part of a specific team in a match. Each queue must have at least one team.

Rules - Specifies how groups should be placed into teams and matches. Rules have different effects, such as requiring a minimum difference between specific attributes (eg. skill level)., specifying what roles a user can be, or the minimum difference in team size. Each queue can be configured with multiple rules to create complex matchmaking requirements.

## Groups

Groups are an immutable collection of players associated with a specific games. Players can be a part of only one group at a time and are automatically removed from previous groups when added to a new group. Groups with zero players are automatically deleted. While groups primarily exist to power matchmaking, they can also be used for other purposes, such as a simple in-game party system. (Airship already has a global party system, more info [here](/platform-services/parties)).&#x20;

A group can have one of 3 states:&#x20;

| Status     | Description                                                                                                                                       |
| ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
| `IDLE`     | No action is being performed. The group is in an idle state.                                                                                      |
| `IN_QUEUE` | The group is currently in a queue and waiting for a match.                                                                                        |
| `IN_MATCH` | The group is currently assigned to a match. Players in the group are expected to be in their assigned match server until the match server closes. |

A group can be in only one queue at a time and will remain in that queue until either a match is made or the request expires (about 30 minutes). To join another queue, you will either need to call `Leave Queue` or create a new group.

Players are allowed to be part of a group even if they are not playing the game. Members that are not in the game will have their "active" value set to false. If any players in the group are inactive, the group will be unable to matchmake. If a group member becomes inactive while their group is in queue, the group will automatically leave the queue.

## Queues

Queues are a collection of configuration that can be used to define a specific game mode or other concept that players can matchmake for. Each queue is separate and groups can only be part of one queue at a time.

Queues can be created on the [Create website](https://create.airship.gg). You must create a queue configuration to use Matchmaking.

## Teams

The team configuration for a queue determines the number of teams the queue has, as well as the minimum and maximum number of players for each team. Teams can be used to represent traditional two team games (Red vs. Blue team) or can represent other game modes such as Battle Royal (25 teams of 4), or asymmetric teams (one vs many). You must always have at least one team.

Each team defined in the configuration is created by selecting groups waiting in the queue. A group will never be split between teams. Keep this in mind, as groups larger than the max size for teams in a queue will not be able to find matches.

## Rules

### Difference Rule

Specifies a maximum difference between groups either at a match level (all groups) or a team level.

<table><thead><tr><th width="229">Field</th><th>Description</th></tr></thead><tbody><tr><td><strong>Attribute</strong></td><td>The attribute to compare. This can be any attribute that is present on the matchmaking group specified when joining the queue.</td></tr><tr><td><strong>Difference</strong></td><td>Maximum difference that can exist between groups for the specified group attribute.</td></tr><tr><td><strong>Scope</strong></td><td>The scope of the rule. "Match" will compare the differences for all groups in the match. "Team" will compare the differences for groups within the same team.</td></tr><tr><td><strong>Seconds Until Optional</strong></td><td>The amount of time in seconds until this rule no longer applies. Use this to loosen rule restrictions.</td></tr></tbody></table>

#### Example: Skill Based Matchmaking

Assuming a DifferenceRule with attribute set to "skill".

```typescript
// Specify the skill attribute at the group level
Platform.Server.Matchmaking.JoinQueue({
    groupId: groupId,
    queueId: "my-skill-based-queue",
    attributes: {
        "skill": 1234
    }
}).await();
```

```typescript
// If you have multiple players each with their own skill you will need to aggregate
// the skill values into one value (such as taking the average)

const numPlayers = users.length; // Assuming users already exist
const totalSkill = users.reduce((user, acc) => user.skill + acc, 0);
const avgSkill = totalSkill / numPlayers;
await Platform.Server.Matchmaking.JoinQueue({
    groupId: groupId,
    queueId: "my-skill-based-queue",
    attributes: {
        "skill": avg_skill
    }
});
```

### Match Set Rule

Compares sets of values looking for a minimum number of similarities. Useful for findings groups that share: favorite maps, purchased content, game modes, etc.

<table><thead><tr><th width="224">Field</th><th>Description</th></tr></thead><tbody><tr><td><strong>Attribute</strong></td><td>The attribute to compare. This can be any attribute containing an array of strings that is present on the matchmaking group specified when joining the queue.</td></tr><tr><td><strong>Minimum Size</strong></td><td>Minimum number of elements required to be matching between groups (set intersection). </td></tr><tr><td><strong>Seconds Until Optional</strong></td><td>The amount of time in seconds until this rule no longer applies. Use this to loosen rule restrictions.</td></tr></tbody></table>

#### Example: Selected Map Modes

Assuming a MatchSetRule with attribute set to "favoriteMaps" and difference set to 1.

```typescript
await Platform.Server.Matchmaking.JoinQueue({
    groupId: groupId,
    queueId: "my-favorite-map-queue",
    attributes: {
        "favoriteMaps": ["dust2", "rust", "strike-at-karkand"]
    }
});
```

### String Equality

Requires that all groups in the specified scope (match or team) have the same value for an attribute. With scope = match, this is useful for restricting a match to a certain type of player (eg. diamond rank)\
With scope = team, this is useful for clan based matchmaking, location vs. location, etc.&#x20;

<table><thead><tr><th width="224">Field</th><th>Description</th></tr></thead><tbody><tr><td><strong>Attribute</strong></td><td>The attribute to compare. This can be any attribute containing a string that is present on the matchmaking group specified when joining the queue.</td></tr><tr><td><strong>Minimum Size</strong></td><td>Minimum number of elements required to be matching between groups (set intersection). </td></tr><tr><td><strong>Scope</strong></td><td>The scope of the rule. "Match" will require equality for all groups in a match. "Team" will require equality for all groups on a specific team, other teams may have different values (can be required to be different with the property <code>Other Teams Should Be Different</code>)</td></tr><tr><td><strong>Other Teams Should Be Different</strong></td><td>When Scope = Team, used to require that no teams in a match share the same team equality value. This is useful for clan based matchmaking where you want Clan A vs. Clan B and want to ensure A and B are not the same value.</td></tr><tr><td><strong>Seconds Until Optional</strong></td><td>The amount of time in seconds until this rule no longer applies. Use this to loosen rule restrictions.</td></tr></tbody></table>

#### Example: Clan Based Matchmaking

Assuming a StringEquality rule with attribute set to "clan", scope set to "team" and other teams should be different set to true:

```typescript
await Platform.Server.Matchmaking.JoinQueue({
    groupId: groupId,
    queueId: "clan-4v4",
    attributes: {
        "clan": "fightingFrogs"
    }
});
```

### Team Fixed Roles

Requires each player on a team be assigned a role. Useful in role based game modes. Players can be automatically assigned a role if none is specified with the property `Automatically Assign Roles`

<table><thead><tr><th width="224">Field</th><th>Description</th></tr></thead><tbody><tr><td><strong>Teams</strong></td><td>The teams that this rule applies to.</td></tr><tr><td><strong>Attribute</strong></td><td>The attribute where the role will be specified. This can be any attribute containing a string that is present on the matchmaking <code>Player</code> specified when joining the queue.</td></tr><tr><td><strong>Match Roles</strong></td><td>Name: The name of the role that will be present for a player "dps", "healer", etc. <br>Quantity: The number of this role that should be present for a team.</td></tr><tr><td><strong>Automatically Assign Roles</strong></td><td>When a player doesn't already have a role assigned, automatically assign them a role based on whatever roles are not already filled. This can be useful if some players haven't selected the role they want to play or if you want the matchmaker to automatically assign roles to players.</td></tr><tr><td><strong>Seconds Until Optional</strong></td><td>The amount of time in seconds until this rule no longer applies. Use this to loosen rule restrictions.</td></tr></tbody></table>

#### Example: Role Based Matches

Assuming a TeamFixedRoles Rule with Attribute set to "role", match roles set to dps: 1, healer: 1, and `Automatically Assign Roles` checked.

```typescript
await Platform.Server.Matchmaking.JoinQueue({
    groupId: groupId,
    queueId: "clan-4v4",
    members: [
        {
            "uid": user1,
            "attributes": {
                "role": "dps"
            },
        }
    ]
});
```

### Team Size Balance

Used to limit the difference between team sizes in a match. Since teams can have variable minimum and maximum sizes based on expansion rules, this rule prevents creating matches where the size difference between the teams in a match is too large.

<table><thead><tr><th width="224">Field</th><th>Description</th></tr></thead><tbody><tr><td><strong>Difference</strong></td><td>The maximum size difference between two teams.</td></tr><tr><td><strong>Seconds Until Optional</strong></td><td>The amount of time in seconds until this rule no longer applies. Use this to loosen rule restrictions.</td></tr></tbody></table>

No attributes are specified at a group / player level for this rule.&#x20;

### Region Priority

Prioritizes low latency matches by matchmaking groups in their lowest latency regions first. Region priority sorts the latency to each region for a group into a list with the lowest latency first. It will start matchmaking the group in only the first region and will add the next region every time "Wait Per Region" elapses.  Groups will still prioritize the lower latency regions first even if they begin matchmaking in multiple regions.

<table><thead><tr><th width="224">Field</th><th>Description</th></tr></thead><tbody><tr><td><strong>Wait Per Region</strong></td><td>The amount of time in seconds to wait before adding an additional matchmaking region.</td></tr><tr><td><strong>Seconds Until Optional</strong></td><td>The amount of time in seconds until this rule no longer applies. Use this to loosen rule restrictions.</td></tr></tbody></table>


# External Services

Game servers can make web requests to external API's using the built-in `HttpManager`. Each request is signed and can be validated by the service you are calling, see [#verifying-gameserver-http-requests](#verifying-gameserver-http-requests "mention") below.

## Overview

```typescript
// Web Requests can only be made on the gameservers. Requests made on the client will fail.
if (!Game.IsServer()) return;

let getResult = HttpManager.GetAsync("https://jsonplaceholder.typicode.com/todos/1");
print(getResult.statusCode, getResult.data);

let postResult = HttpManager.PostAsync("https://jsonplaceholder.typicode.com/posts", json.encode({
	title: 'foo',
	body: 'bar',
}));
print(postResult.statusCode, postResult.data);


```

### Supported Methods

```typescript
GetAsync(url: string, headers: string): HttpResponse;
GetAsync(url: string): HttpResponse;
PatchAsync(url: string, data: string): HttpResponse;
PatchAsync(url: string, data: string, headers: string): HttpResponse;
PostAsync(url: string, data: string): HttpResponse;
PostAsync(url: string, data: string, headers: string): HttpResponse;
PutAsync(url: string, data: string): HttpResponse;
PutAsync(url: string, data: string, headers: string): HttpResponse;
PutAsync(options: RequestHelper, headers: string): HttpResponse;
DeleteAsync(url: string): HttpResponse;
DeleteAsync(url: string, headers: string): HttpResponse;
```

### Verifying GameServer HTTP Requests

Requests originating from a GameServer will include an additional header called: `x-airship-signature` containing a JWT with request details including:

```typescript
{
  "jti": string, // JWT ID - UUID e.x. 8e2b6b98-14ba-4724-b95b-3627b6d48d5b
  "iat": number, // u64 - Timestamp this jwt was issued, in seconds since Unix Epoch
  "exp": number, // u64 - Timestamp this jwt expires, in seconds since Unix Epoch
  "hostname": string, // e.x. "mywebsite.test" Will include port if not https, http 443, 80
  "path": string, // e.x. "/path/123" excludes query params
  "method": string, // GET, POST, etc.
  "gameId": string, // This should match your gameId on create.airship.gg
  "serverId": string,
  "sceneId": string, // The default starting scene of the server (doesn't update if changed)
  "region": string,
  "organizationId": string,
  "type": "game-server"
}
```

Each JWT is signed with a specific public key that can be identified in the header using `kid`:

```json
{
  "typ": "JWT",
  "alg": "ES256",
  "kid": "f24d25f2-e49b-424b-8e61-cf9c8219b332"
}
```

Using the `kid` you can validate the JWT against Airship public keys using our JWKS endpoint: <https://airship.gg/.well-known/jwks.json>

Read more here: <https://stytch.com/blog/understanding-jwks/>

Examples verifying a JWT using JWKS can be found here: <https://github.com/panva/jose/blob/main/docs/jwks/remote/functions/createRemoteJWKSet.md>

When validating the token, ensure the JWT is signed by an Airship public key and ensure the hostname / path matches your API url.


# Extending the editor

Since Airship uses Unity, most of the custom editor features will work as-is. Some examples of features you might may want to add to your project:

* [Adding editor menus](https://docs.unity3d.com/6000.0/Documentation/ScriptReference/MenuItem.html)

Airship also has our own analogous versions of Unity features such as

* [Adding custom property inspectors for `AirshipBehaviour`s](/editor-extensions/custom-inspectors-c)

### Before you begin

If you are planning to write C# scripts for the editor, it's recommended you turn *off* the TypeScript compiler *while* you write C# editor code.&#x20;

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FbLBxlJOoZaoIudcr1Nw2%2Fimage.png?alt=media&amp;token=5b06b4da-9cf7-4889-8cd5-448d9f026dbc" alt=""><figcaption><p>How to access the TypeScript service settings</p></figcaption></figure>

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FJpajqmA3QCFk4gpGC1bv%2Fimage.png?alt=media&amp;token=97f70b39-b5f9-4773-a2a0-178c7c9e3ede" alt=""><figcaption></figcaption></figure>

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2Ffqjkkws1NX2J5AjnnHLj%2Fimage.png?alt=media&amp;token=e7e9d22d-b7dc-4de0-a680-49a0c1d67b80" alt=""><figcaption><p>Developer Options setting, which will allow more settings for the TypeScript compiler</p></figcaption></figure>

This will change the TypeScript menu to add options to start/stop the compiler. This can be utilized to stop the compiler recompiling each time you make a C# change.

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FhyBM5Cw5wmnGqdTgFbQX%2Fimage.png?alt=media&amp;token=e87f1d3a-3880-4dd3-8162-db26e5c304fe" alt=""><figcaption><p>TypeScript developer mode</p></figcaption></figure>

### Airship Editor C# API

Airship has the following user editor APIs you can use:

* \
  `AirshipSerializedProperty`  and `AirshipSerializedObject` for handling Airship Behaviour property serialization
* `AirshipCustomEditors` for querying the registered custom inspectors for AirshipBehaviours
  * See [AirshipBehaviour inspectors](/editor-extensions/custom-inspectors-c) for how to add custom editors
* `AirshipType` which is the Airship version of `Type` for TypeScript-based types.
  * Types can be queried using `AirshipType.GetType(name)`&#x20;
* `AirshipEditorGUI` - for drawing editor properties for `AirshipSerializedProperty` instances using IMGUI.
* `AirshipGUI` for general Airship GUI state
* `TypescriptService` for general TypeScript APIs
* `TypescriptProjectsService.Project` for querying the project settings
* `TypescriptCompilationService` for querying the compiler state


# Custom Inspectors (C#)

{% hint style="info" %} <i class="fa-flask-round-potion">:flask-round-potion:</i> This is currently a beta feature being tested in Airship and includes a rewrite of the inspector system. The API is subject to change.
{% endhint %}

While Airship will generate a default inspector for `AirshipBehaviour` components, you may want to create a custom inspector to:

* Create a more user-friendly interface for complex components
* Organize and group properties
* Conditionally show/hide UI based on user choices.

If you need to just *categorize or add constraints* to properties, you can refer to [Using Component Decorators](/typescript/airshipbehaviour/adding-inspector-properties#organizing-your-properties). <br>

{% hint style="info" %}
Currently editor scripts can only be written through the C# *AirshipEditor* API. Support for TypeScript-based editor scripts may come in future.
{% endhint %}

You can declare an `AirshipBehaviour` as per usual -

```typescript
export default class ExampleComponent extends AirshipBehaviour {
    public name = "Bob";
    public age = 20;
    public favouriteColor = Color.blue;
}
```

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FVGzdhsE8tgAZEH8KkY0c%2Fimage.png?alt=media&amp;token=0039e4d5-1fdc-4735-aa8a-ea5d34871f61" alt=""><figcaption><p>Default inspector for the "Example Component" object</p></figcaption></figure>

### Creating a custom inspector script

{% hint style="info" %}
Airship only supports using IMGUI for custom inspectors at this time.
{% endhint %}

Creating a custom inspector for any *Airship* serialized object is pretty straightforward. You will need to create a class that derives from `AirshipEditor` and add the `AirshipEditor` attribute to it. This will let Airship know what class this custom inspector represents.

{% code title="Assets/Editor/ExampleComponentInspector.cs" %}

```csharp
[CustomAirshipEditor("ExampleComponent")]
public class ExampleComponentEditor : AirshipEditor {
    public override void OnInspectorGUI() {
        EditorGUILayout.LabelField("This is a custom inspector");
    }
}
```

{% endcode %}

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2F01UdPrto3finMYspc9Ah%2Fimage.png?alt=media&amp;token=6adffd7e-f356-4225-b4b1-13bc0f803967" alt=""><figcaption><p>Custom Inspector with label</p></figcaption></figure>

{% hint style="info" %}
You should make sure that your editor scripts are in an *Editor* folder.
{% endhint %}

`AirshipEditor` is similar to `UnityEngine.Editor` and contains Airship parallels to the unity custom editor API

* It contains a `serializedObject` and `target` property
* You can access airship properties via `serializedObject.FindAirshipProperty("propertyName")` - this will return an `AirshipSerializedValue` which you can use to check or modify the property with; similar to `SerializedProperty`.
* You can render properties using the Airship editor system using `AirshipEditorGUI.PropertyField(airshipProperty)` by default, however you are not limited to it.

### Example 1: Showing/Hiding properties based on user choices

There may be cases where you want to show/hide properties based on what the user has selected

{% code title="Assets/Code/ExampleComponent.ts" %}

```typescript
export default class ExampleComponent extends AirshipBehaviour {
	public name: string;
	public color = Color.blue;

	public hiddenProperties = false;
	public hiddenNumber: number;
	public hiddenBoolean: boolean;
	public hiddenString: string;
}

```

{% endcode %}

{% code title="Assets/Editor/ExampleComponentInspector.cs" %}

```csharp
[CustomAirshipEditor("ExampleComponent")]
public class ExampleComponentEditor : AirshipEditor {
    public override void OnInspectorGUI() {
        // PropertyField here can be used as shortcut to show property fields
        PropertyField("name");
        PropertyField("color"); 
        
        // If the property is a boolean one, it can be used to conditionally check
        if (PropertyField("hiddenProperties")) {
            // Properties can also be queried using 'FindAirshipProperty'
            var secretValue = serializedObject.FindAirshipProperty("hiddenNumber");
            PropertyField(secretValue);
            
            // values of properties can be queried as well!
            if (secretValue.numberValue > 100) {
                EditorGUILayout.LabelField("The number is greater than 100!");
            }
            // You can also show multiple properties in one line
            PropertyFields("hiddenBoolean", "hiddenString");
        }
    }
}

```

{% endcode %}

The resulting inspector behaviour:

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FgrfnUrIOzBv7xCpDOqwp%2Fimage.png?alt=media&amp;token=d3bb8b36-7a64-4a3e-89ed-15d13a1ff6fc" alt=""><figcaption><p>With 'hidden properties' unchecked<br></p></figcaption></figure>

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FWJg38PL5A2yWPWFL7q5M%2Fimage.png?alt=media&amp;token=0c3ed210-94fb-4ba0-a84e-3c403816e445" alt=""><figcaption><p>With 'hidden properties' checked</p></figcaption></figure>

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FQ5BnS8UrnAYJxl6Ghi9o%2Fimage.png?alt=media&amp;token=b0a3f26d-8121-4387-b8fc-dc6ef4900535" alt=""><figcaption><p>With 'hidden number' > 100</p></figcaption></figure>


# Displaying properties of other components

There may be cases where you want to "embed" another component's properties in your inspector.

{% code fullWidth="false" %}

```csharp
// componentReference here would be any reference to an AirshipBehaviour
var componentProperty = serializedObject.FindAirshipProperty("componentReference");
if (componentProperty.objectReferenceValue is AirshipComponent component) {
    // this is similar to serializedObject, but pointing at a different component
    var componentSerializedObject = new AirshipSerializedObject(component);
    
    // Then you can use componentSerializedObject as you would with serializedObject
    
    // ApplyModifiedProperties *must* be called otherwise the properties will not change.
    componentSerializedObject.ApplyModifiedProperties();
}
```

{% endcode %}

If you want to use the custom inspector (if you have one defined for the component) you can do

{% code fullWidth="false" %}

```csharp
var componentProperty = serializedObject.FindAirshipProperty("componentReference");
if (componentProperty.objectReferenceValue is AirshipComponent component) {
    // garb the custom editor and render it
    var componentEditor = AirshipCustomEditors.GetEditor(component);
    componentEditor.OnInspectorGUI();
    // Apply any modified properties from the above call
    componentEditor.serializedObject.ApplyModifiedProperties();
}

```

{% endcode %}


# Editor API (C#)

### <mark style="color:$warning;">AirshipType</mark>

Used to query the types in Airship

```csharp
var exampleComponentType = AirshipType.GetType("ExampleComponent");
```

|                                                                                                                       |                                                                                                  |
| --------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------ |
| <mark style="color:$primary;">string</mark> Name                                                                      | The name of the type                                                                             |
| <mark style="color:$primary;">string</mark> RuntimePath                                                               | The Runtime Lua path this type is associated with                                                |
| <mark style="color:$primary;">string</mark> AssetPath                                                                 | The Editor asset path of the file that contains this type                                        |
| <mark style="color:$primary;">string</mark> UniqueId                                                                  | A unique identifier for this type                                                                |
| <mark style="color:$warning;">AirshipType</mark>\[] BaseTypes                                                         | The types this type inherits                                                                     |
| <mark style="color:$warning;">AirshipDeclarationType</mark> DeclarationType                                           | The declaration type of this type - e.g. Behaviour, Enum, ScriptableObject or SerialziableClass. |
| <mark style="color:$primary;">bool</mark> IsAssignableFrom(<mark style="color:$warning;">AirshipType</mark> baseType) | Used to check if this type is, or inherits another type                                          |

### <mark style="color:$warning;">AirshipCustomEditors</mark>

{% columns %}
{% column %} <mark style="color:$primary;">static</mark> <mark style="color:$warning;">AirshipEditor</mark> GetEditor(<mark style="color:$warning;">AirshipComponent</mark> component)
{% endcolumn %}

{% column %}
Used to get the editor for the specified component
{% endcolumn %}
{% endcolumns %}

### <mark style="color:$warning;">AirshipEditor</mark>

Derive from this base class to create a custom inspector for an `AirshipBehaviour`

```csharp
[AirshipCustomEditor("TypeScriptClassName")]
public class ExampleComponentEditor : AirshipEditor {
    public override void OnInspectorGUI() {
        
    }
}
```

|                                                                               |                                              |
| ----------------------------------------------------------------------------- | -------------------------------------------- |
| <mark style="color:$warning;">AirshipSerializedObject</mark> serializedObject | The serialized object                        |
| <mark style="color:$warning;">AirshipScript</mark> script                     | The script the editor is for                 |
| UnityEngine.<mark style="color:$warning;">Object</mark> target                | The target object for this editor            |
| <mark style="color:$primary;">void</mark> OnInspectorGUI()                    | The IMGUI inspector lifecycle for the editor |

### <mark style="color:$warning;">AirshipEditorGUI</mark>

Contains IMGUI drawing methods for Airship

<table><thead><tr><th></th><th></th></tr></thead><tbody><tr><td><mark style="color:$primary;">static void</mark> HorizontalLine(<mark style="color:$warning;">Color</mark> color = default, <mark style="color:$primary;">int</mark> thickness = 1, <mark style="color:$primary;">int</mark> padding = 10, <mark style="color:$primary;">int</mark> margin = 0)</td><td>Draws a horizontal line</td></tr><tr><td><mark style="color:$primary;">static bool</mark> PropertyField(<mark style="color:$warning;">AirshipSerializedProperty</mark> property)</td><td><p>Draws the given <code>AirshipSerializedProperty</code>.</p><pre class="language-csharp"><code class="lang-csharp">var exampleProperty = serializedObject.FindAirshipProperty("exampleProperty");
AirshipEditorGUI.PropertyField(exampleProperty);
</code></pre></td></tr><tr><td><mark style="color:$primary;">static  bool</mark> PropertyField(<mark style="color:$warning;">GUIContent</mark> label, <mark style="color:$warning;">AirshipSerializedProperty</mark> property)</td><td>Draws the given <code>AirshipSerializedProperty</code> with a custom label.</td></tr><tr><td><mark style="color:$primary;">static int</mark> BeginTabs(<mark style="color:$primary;">int</mark> selectedIndex, <mark style="color:$warning;">GUIContent</mark>[] tabs)</td><td><p>Will draw a tab view, must contain an <code>EndTabs</code> call at the end of the content.</p><pre class="language-csharp"><code class="lang-csharp">selectedTabIndex = AirshipEditorGUI.BeginTabs(selectedTabIndex, new [] {
    new GUIContent("Tab 1"),
    new GUIContent("Tab 2"),
});
if (selectedTabIndex == 0) {
    // render content of tab #1
} else if (selectedTabIndex == 1) {
    // render content of tab #2
}
AirshipEditorGUI.EndTabs();
</code></pre></td></tr><tr><td><mark style="color:$primary;">static void</mark> EndTabs()</td><td></td></tr><tr><td><mark style="color:$primary;">static void</mark> BeginGroup(<mark style="color:$warning;">GUIContent</mark> label)</td><td>Begin a group (will be "grouped" in a padded frame)</td></tr><tr><td><mark style="color:$primary;">static void</mark> EndGroup()</td><td>Ends the previous group scope</td></tr></tbody></table>


# Quick Overview

A brief breakdown of how Airship games are built

## Unity Editor

Airship games are made in the Unity Engine. It comes with many powerful tools for creating games and there are many resources online for learning how to use it. Below is a breakdown of the basics but if you are new to Unity we suggest looking through the basics on Unity Learn:

[Unity Learn: Explore The Editor](https://learn.unity.com/pathway/unity-essentials/unit/editor-essentials/tutorial/explore-the-editor-interface-1-1)

{% hint style="info" %}
Airship DOES NOT USE C# so code in Airship will look different, though you can access the same API that Unity C# does so coding tutorials still may be helpful.&#x20;
{% endhint %}

## Typescript

Instead of C# scripts you will be working exclusively in [Typescript for Airship](/typescript/typescript-overview) projects. Typescript files are placed inside the Unity Project just like other assets and are automatically compiled. To create a new file you can right click in your project and select `Create -> Airship -> Typescript File`. This will give you a default [AirshipBehaviour](/typescript/airshipbehaviour) script. Once you make an AirshipBehaviour you can add it as a component to a game object in your scene. Do this by selecting a game object and clicking `Add Airship Component` in the Inspector

```typescript
export default class DefaultAirshipComponent extends AirshipBehaviour {
	override Start(): void {
		print("Hello, World! from DefaultAirshipComponent!");
	}
}

```

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FOEghxsjVtncHD5ezCW7a%2FScreenshot%202025-02-04%20170846.png?alt=media&amp;token=a676d67a-08d6-4cdf-ab0d-863a6870d125" alt="" width="298"><figcaption></figcaption></figure>

## Mirror Networking

For gameplay networking Airship uses Mirror. It is an open source multiplayer solution. Objects are synced between clients and the server via [Network Identities](/networking/network-identity) and there are many helpful ways to sync data with [Networked Functions](/networking/network-functions) and additional components such as [Network Transforms](/networking/network-transform).The mirror documentation can be found here:

[Mirror Docs](https://mirror-networking.gitbook.io/docs)

## Publishing

Once you have[ tested your game locally](/networking/local-server-mode) you will want to see your game in action! [Publishing](/publishing/publish-game) is fast and easy and can instantly be played on Steam through the Airship game. You can setup your games info via a web portal at <https://create.airship.gg/>


# DataType Math

The API exposed to Airship contains data types from Unity such as (and not limited to) `Vector3`, `Vector2` and `Quaternion`.

Due to limitations with TypeScript, there is no operator overloading functionality.

To get around this and do mathematical operations on datatypes, the following methods are available where applicable:

* `a.add(b)` (a + b)
* `a.sub(b)` (a - b)
* `a.mul(b)` (a \* b)
* `a.div(b)` (a / b)

```typescript
const v1 = new Vector3(1,0,1);
const v2 = Vector3.up; //(0,1,0)
const v3 = v1.add(v2); //Equals (1,1,1)
```


# Random

For simple randomization `math.random()` will work. For more advanced randomization (such as seeded instances), you can use the `Random` class.

```typescript
// Simple
const randomNumber = math.random(); // 0-1

// Advanced
const rng = new Random(optionalSeed);
rng.Number(); // 0-1
rng.Number(10); // 0-10
rng.Number(10, 20); // 10-20
rng.Int(5, 15); // 5-15, integer
rng.UnitVector3(); // Random unit vector3
rng.UnitVector2(); // Random unit vector2
rng.PickItem(arr); // Random item from array
rng.PickItemWeighted(arr, weights); // Random weighted item
rng.ShuffleArray(arr); // Fisher-yates shuffle in-place
rng.Clone(); // Clone current RNG state into a new RNG object
```

{% hint style="info" %}
PickItemWeighted is optimized for immutable weights. For the best performance, ensure you call `table.freeze` on your weights array.
{% endhint %}

Example usage:

```typescript
//Create the data
enum Rarity {
    Common,
    Rare,
    Legendary,
}

interface Item {
    name: string;
    rarity: Rarity;
}

const items: Item[] = [
    {
        name: "Leather Hat",
        rarity: Rarity.Common,
    },
    {
        name: "Golden Glove",
        rarity: Rarity.Rare,
    },
    {
        name: "Diamond Bat",
        rarity: Rarity.Legendary,
    },
];

// Freeze a set of values to act as the weights for randomization
const weights = table.freeze(
    items.map((item) => {
        switch (item.rarity) {
            case Rarity.Common:
                return 15;
            case Rarity.Rare:
                return 4;
            case Rarity.Legendary:
                return 1;
        }
    }),
);

//Create a new random instance
const rng = new Random();
//Get a single item out of the array using weighted randomization
const randomItem = rng.PickItemWeighted(items, weights);
```


# Resources Folder

In Unity, any folder name `Resources` will be setup its files to be loaded at runtime via local paths.&#x20;

To load these assets in Airship use the `Asset` class:

```typescript
const myPrefab: GameObject =  Asset.LoadAsset("Local/Path/From/Resources.prefab");
```

{% hint style="info" %}
Look to the Unity [Resources Folder](https://docs.unity3d.com/ScriptReference/Resources.html) page for more information.
{% endhint %}


# Physics Settings

## Editor Values

Unity's physics engine can be customized through the project settings panel. Only some values are available for games to customize in editor. Other values will need to be modified at runtime via TS code or not at all.

**Available to Customize In Editor:**

<div align="left"><figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2Fz7HrRsjYrwYDpzcDrcsx%2Fimage.png?alt=media&amp;token=936b80c6-5e1d-4c21-82b9-9769391cb95b" alt="" width="375"><figcaption></figcaption></figure></div>

* Gravity
* Bounce Threshold
* Default Max Depenetration Velocity
* Sleep Threshold
* Default Contact Offset
* Default Solver Iterations
* Default Solver Velocity Iterations
* Queries Hit Backfaces
* Queries Hit Triggers
* Game Layer Physics Matrix (Any modifications to the core layers in the physics matrix will be overwritten)

## Editing In Code

You can edit physics settings at runtime just like you would in C# by accessing the Physics static object.&#x20;

```
Physics.gravity = new Vector3(0,-9001, 0);
```

To modify the physics matrix in code you can use

```typescript
Physics.IgnoreLayerCollision(17, 18, false);
```

{% hint style="info" %}
You can reset all physics settings to the Airship default settings by using the menu button **Airship->Misc->Reset Physics To Airship Defaults**
{% endhint %}


# Physics Layers

How to work with Unity Game Object layers in Airship

Airship reserves layers 0-16 for internal use. Every other layer is available for use by game devs.

These layers are named GameLayer\[0-31] but can be renamed as you see fit.&#x20;

You may also change the Physics Matrix for these layers. Read more about the  [Physics Matrix here.](https://docs.unity3d.com/Manual/LayerBasedCollision.html)

In Typescript you can use the layers via their name or index.  You can easily get their index with the GameLayer static Enum.

```typescript
// Create a mask from layer names
const layerMask = LayerMask.GetMask("GameLayer0", "GameLayer1");

// Check if an object is a game layer
if (this.gameObject.layer === GameLayer.GAMELAYER_0) {

	//Raycast with a game layer mask
	if (Physics.Raycast(this.transform.position, this.transform.forward, 10, layerMask)) {
		print("Hit a game layer object");
	}
	
}
```

{% hint style="info" %}
You can revert core layers you have renamed by using the menu button&#x20;

**Airship->Misc->Repair Project**&#x20;
{% endhint %}


# Animation Events

Create and capture animation events to run functions in code when your animation hits a specific location.

## Overview

In Airship animation events are passed to Typescript through the AnimationEventListener component. If you add this component to your animator it will pass along events from your animations. Airship Characters have this component by default.

{% hint style="info" %}
Naming is important here. All animation events must fire the function "TriggerEvent" to be passed into Typescript.&#x20;
{% endhint %}

## Create Animation Events

To setup an event use Unity's animation event system either in the animation clip itself using the animation window, or on an FBX using the inspector window.&#x20;

1. Create a new animation event
2. Give it the function `TriggerEvent`
3. Set the triggers key to be whatever you would like to identify it by

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FHwaP7EaDsgAyzkhOZ2Yh%2Fimage.png?alt=media&amp;token=c10d5e05-7b06-41b3-8f54-3a22b308bee2" alt="" width="344"><figcaption><p>MyAnimationEvent On Animation Clip</p></figcaption></figure>

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FicYlx72PWBbH5nUqr1Xa%2Fimage.png?alt=media&amp;token=a2f94ffd-5862-4e2d-8660-e8519fc220fb" alt="" width="355"><figcaption><p>MyAnimationEvent On FBX Animation</p></figcaption></figure>

## Listening To Animation Events

To listen to events in Typescript, get the component reference for the AnimationEventListener, then connect to the OnAnimationEvent Signal on Character.animator:

```typescript
//Get the component (or you can setup a reference if in an AirshipBehaviour)
const events = this.gameObject.GetComponent<AnimationEventListener>();
if(events){
	//Connect to simple events
	events.OnAnimEvent((key)=>{
		//Key is the string value you specify in editor
		if(key === "MyAnimationEvent"){
			///Do Stuff
			print("Heard my event!");
		}
	})
}
```

{% hint style="info" %}
Characters by default have an AnimationEventListener and can be listened to through a signal on Character.animation.OnAnimationEvent which is more performant than directly accessing the characters AnimationEventListener.

Read more on the [Character Animations Page](/characters/character-animations)
{% endhint %}

### Optional - Pass Data With Event

If you need additional data passed along with the event, you can include an AnimationEventData scriptable object.

1. In your project, right click to `Create -> Airship -> Animation Event Data`
   1. Fill in the objects data with whatever you want to receive in TS
2. On your animation, Set the event function to `TriggerEventObj`&#x20;
3. Set the Object variable to the Animation Event Object you created

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2Fsa0XqMd1cqPJeh5a9EvH%2Fimage.png?alt=media&amp;token=59a83a49-ae4b-4145-96c5-645d65113206" alt="" width="375"><figcaption></figcaption></figure>

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2Ft13GZ4VJQtxEdeuHUXA8%2Fimage.png?alt=media&amp;token=dbcf49a4-14fc-4a18-9a4a-2ba23aa65d4b" alt=""><figcaption></figcaption></figure>

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2F0C1RvXNmW1WyeikH5MOQ%2Fimage.png?alt=media&amp;token=4d723645-0643-4503-9256-ef2950e9e56f" alt=""><figcaption></figcaption></figure>

Now to receive this event in Typescript

```typescript
//Get the component (or you can setup a reference if in an AirshipBehaviour)
const events = this.gameObject.GetComponent<AnimationEventListener>();
if(events){
	//Connect to object event
	events.OnAnimObjEvent((data)=>{
		//key is used to identify the event
		if(data.key === "MyAnimationEventObj"){
			///Do Stuff with the extra data
			print("New Float: " + data.floatValue);
		}
	})
}
```


# User Input

Listening to user input is done through various input classes. Below are a few high-level examples of using these input classes.

For more complete documentation, please look through the other input documentation pages in this section.

### [Actions](/unity-for-airship/user-input/actions)

```typescript
// Define an action
Airship.Input.CreateAction("Jump", Binding.Key(Key.Space));

// Listen to using the action
Airship.Input.OnDown("Jump").Connect(() => {
    print("Jump pressed")
});
```

### [Keyboard](/unity-for-airship/user-input/keyboard)

```typescript
// Listening for key down:
Keyboard.OnKeyDown(Key.E, (event) => {
    print("Key E down");
});

// Checking if a key is currently down:
if (Keyboard.IsKeyDown(Key.E)) print("Key E down");
```

### [Mouse](/unity-for-airship/user-input/mouse)

```typescript
// Listen for left button down and print out current screen position:
Mouse.onLeftDown.Connect(() => {
const screenPosition = Mouse.position;
    print("Left mouse button down", screenPosition);
});

// Left button up:
Mouse.onLeftUp.Connect(() => {
    print("Left mouse button up");
});

// Mouse moved:
Mouse.onMoved.Connect((screenPosition) => {
    print("Mouse moved", screenPosition);
});
```


# Actions

### Basic Actions

Actions let you define input bindings that your players can rebind from the settings menu.

```typescript
// Define an action
Airship.Input.CreateAction("Dash", Binding.Key(Key.LeftShift));

// Listen to using the action
Airship.Input.OnDown("Dash").Connect(() => {
    print("Dash!");
});
```

### Core Actions

You can also hook into core actions or disable them in your game. Listening to core actions allows you to share a player's preferred keybinds from other games. The `CoreAction` enum holds the ID of each core actions in Airship.

```typescript
// Disable core jump & sprint actions
Airship.Input.DisableCoreActions([CoreAction.Jump, CoreAction.Sprint]);

// Listen to core primary action (by default left click)
Airship.Input.OnDown(CoreAction.PrimaryAction).Connect(() => {
    print("Swing sword");
});
```

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2Fsxw75KqvUghheToIgjXs%2FScreenshot%202024-09-13%20at%202.02.00%20PM.png?alt=media&amp;token=9d140b8a-93c9-4c2c-8cb9-79274c7237a2" alt=""><figcaption><p>Settings menu after running the code snippets. Players can rebind any action without any work on your end.</p></figcaption></figure>

### Modifier Keys

For multi-key input you can create an action with a modifier key. Players can also rebind any actions to include a modifier.

```typescript
// Dash on Shift+G
Airship.Input.CreateAction("Dash", Binding.Key(Key.G, ModifierKey.LeftShift));

// Print out key display
const dashAction = Airship.Input.GetActions("Dash")[0]
const keyDisplay = dashAction.binding.GetDisplayName();
print("Press " + keyDisplay + " to dash!")
// prints "Press Left Shift + G to dash!"
```

### Update Action Binding

You can change a binding for a player through code. Unlike when a player changes their settings your binding changes will not be saved for the player beyond this session.

```typescript
dashAction.UpdateBinding(Binding.MouseButton(MouseButton.LeftButton));
```


# Keyboard

Keyboard API is useful for directly accessing keystrokes. If you want players to rebind your input use [Actions](/unity-for-airship/user-input/actions).

## Listening for Key Presses

Use the `OnKeyDown` and `OnKeyUp` methods to listen for key events.

```typescript
Keyboard.OnKeyDown(Key.E, (event) => {
    print("E key down");
});

Keyboard.OnKeyUp(Key.E, (event) => {
    print("E key up");
});

// Optional signal priority:
Keyboard.OnKeyDown(Key.E, (event) => {
    print("E key down, before the other one!");
}, SignalPriority.HIGH);
```

### Disconnecting Listener

Keyboard listeners return a cleanup function. When you no longer need to listen to the key you can call the cleanup function to disconnect your callback.

```typescript
// Listen for one press of "E" -- then disconnect
const disconnectKeyDownE = Keyboard.OnKeyDown(Key.E, (event) => {
    print("E key down");
    // Disconnect this listener
    disconnectKeyDownE();
});
```

## Polling for Keys Down

To check if an individual key is down, call the `IsKeyDown` method. There are also two combination methods, `IsEitherKeyDown` and `AreBothKeysDown`.

```typescript
// Check if single key is down:
if (Keyboard.IsKeyDown(Key.E)) print("E is down");

// Check if at least one of the two keys are down:
if (Keyboard.IsEitherKeyDown(Key.W, Key.UpArrow)) print("Up");

// Check if both keys are down:
if (Keyboard.AreBothKeysDown(Key.S, Key.LeftShift)) print("Save");
```

## Sinking Key Events

It is possible to sink key input events, preventing the event from continuing on to other listeners.

To sink an event, use the `SetCancelled` event method. In cases where event sinking is occurring, it is best to also include the desired `SignalPriority`.

```typescript
Keyboard.OnKeyDown(Key.E, (event) => {
    event.SetCancelled(true);
}, SignalPriority.HIGHEST);
```


# Mouse

### Events

There are individual events for the up and down events for left, right, and middle mouse buttons: `onLeftDown`, `onLeftUp`, `onRightDown`, `onRightUp`, `onMiddleDown`, `onMiddleUp`.

```typescript
Mouse.onLeftDown.Connect(() => {
    print("Left button down");
});

Mouse.onLeftUp.Connect(() => {
    print("Left button up");
});
```

### Polling

The state of each button can also be checked with the `IsLeftButtonDown` (et. al.) methods.

```typescript
if (Mouse.IsLeftButtonDown()) {
    print("Left button down");
}

if (Mouse.IsRightButtonDown()) {
    print("Right button down");
}

if (Mouse.IsMiddleButtonDown()) {
    print("Middle button down");
}
```

## Movement

### Events

The `Moved` event fires when the mouse is moved. The `onScrolled` event fires when the scroll wheel is moved.

```typescript
Mouse.onMoved.Connect((screenPosition) => {
    print("Mouse position", screenPosition);
});

Mouse.onScrolled.Connect((delta) => {
    print("Scrolled", delta);
});
```

### Polling

Use the `position` field and `GetDelta` method to retrieve information about mouse movement.

```typescript
// Get current position of mouse:
const screenPosition = Mouse.position;

// Get movement of mouse since last frame:
const delta = Mouse.GetDelta();
```


# Easy Helper Utils

There are several components and scripts that can be helpful when creating your own games. Here is a general break down of several of them.

{% content-ref url="/spaces/IbaXflSJA8L9N9yOx089/pages/J8VEO8CylslXJnlGQWhj" %}
[Material Color URP](/unity-for-airship/easy-helper-utils/material-color-urp)
{% endcontent-ref %}

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2Fa4TRGW6wuffVXdXd6Zn9%2FMaterialColorURP.gif?alt=media&amp;token=f3200ea3-12cf-48a9-aa24-80f18d3ae319" alt="" width="240"><figcaption></figcaption></figure>

{% content-ref url="/pages/tQSrSPmTYpV8iHoxORag" %}
[Easy Motion](/unity-for-airship/easy-helper-utils/easy-motion)
{% endcontent-ref %}

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2F9khGx19wpb004SLORYXJ%2FEasyMotionDemo.gif?alt=media&amp;token=b00a80e4-8969-43e2-8cc1-52733787fa3d" alt="" width="375"><figcaption><p>Easy Motion</p></figcaption></figure>

{% content-ref url="/pages/2mstFeraHSqvvtwDwxTe" %}
[Easy Grid Align](/unity-for-airship/easy-helper-utils/easy-grid-align)
{% endcontent-ref %}

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FRgG6auw42Kh4xzB1bGuU%2FEasyGridAlignDemo.gif?alt=media&amp;token=1f05cc8c-1324-4ddc-915c-7aa8e9d36c82" alt="" width="375"><figcaption><p>Easy Grid Align</p></figcaption></figure>

{% content-ref url="/pages/aNXQSaUU7kN2q1pVdnbc" %}
[Easy Look At](/unity-for-airship/easy-helper-utils/easy-look-at)
{% endcontent-ref %}

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FrPB5dEQMkZsOm2n5zcEl%2FEasyLookAtDemo.gif?alt=media&amp;token=a4e7e0bc-e04f-4937-837d-4cec4a665d8b" alt="" width="375"><figcaption><p>Easy Look At</p></figcaption></figure>

{% content-ref url="/pages/2Mxnj2prksf5KNcl1hhT" %}
[Easy Shake](/unity-for-airship/easy-helper-utils/easy-shake)
{% endcontent-ref %}

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FfZJBbatIZsZ9COJlai0b%2FEasyShakeDemo.gif?alt=media&amp;token=e537c3c8-c777-406c-a02c-dfbde5132409" alt="" width="375"><figcaption></figcaption></figure>

{% content-ref url="/pages/yagrbt8uAYMPKjyNuElQ" %}
[Easy Destroy](/unity-for-airship/easy-helper-utils/easy-destroy)
{% endcontent-ref %}

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FII1sP3AsNzbsW0OIkSVB%2Fimage.png?alt=media&amp;token=04f2f0d0-0ba4-447e-8cf3-b6cb5a522ac2" alt="" width="301"><figcaption><p>Easy Destroy</p></figcaption></figure>

{% hint style="info" %}
Some helpers are C# instead of typescript so they are more performant, can run in Editor mode, and have custom inspectors.&#x20;
{% endhint %}


# Material Color URP

Set the color of a material

Place this component on a renderer's game object to dynamically assign the color value of its materials. It works for multiple materials on one mesh and can also be changed at runtime.&#x20;

{% hint style="info" %}
This script sets the materials `_MainColor` variable via a MaterialPropertyBlock. Use this name in your custom shader to have it support MaterialColorURP.&#x20;
{% endhint %}

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2Fa4TRGW6wuffVXdXd6Zn9%2FMaterialColorURP.gif?alt=media&amp;token=f3200ea3-12cf-48a9-aa24-80f18d3ae319" alt=""><figcaption></figcaption></figure>


# Easy Motion

A c# component that allows you to quickly animate a Transform. Works with linear motion or Sine motion.

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FpLWzv64G3hXBibNbpG6f%2Fimage.png?alt=media&amp;token=aca70c9f-40e1-468d-885e-3b5c5647442a" alt="" width="375"><figcaption></figcaption></figure>

Control Position Rotation and Scale independently.&#x20;

Enable Sine Motion to have the transform osculate instead of continuously move. &#x20;

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2F9khGx19wpb004SLORYXJ%2FEasyMotionDemo.gif?alt=media&amp;token=b00a80e4-8969-43e2-8cc1-52733787fa3d" alt="" width="375"><figcaption><p>Easy Motion</p></figcaption></figure>

{% hint style="info" %}
Use child transforms to layer motions for added effects
{% endhint %}


# Easy Grid Align

A c# component that allows you to quickly align multiple transforms in multiple axis.

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FxXGokeiqT8yAswY9HB5Q%2Fimage.png?alt=media&amp;token=5705ab0e-6f9b-4cbd-aaab-5b0458bfabf2" alt="" width="375"><figcaption></figcaption></figure>

Rebuild in editor to get things positioned how you want, or rebuild in Play mode if you want it to be dynamic.

ContentHolder is the parent transform that holds all of the elements you want aligned. Place child elements here to have them aligned.

NumberOfGridElements is the target Max number of elements in each axis.

Local Grid Element Size is how spaced out each element should be.

The Random offsets let you give variance to each positioned element.&#x20;

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FRgG6auw42Kh4xzB1bGuU%2FEasyGridAlignDemo.gif?alt=media&amp;token=1f05cc8c-1324-4ddc-915c-7aa8e9d36c82" alt="" width="375"><figcaption></figcaption></figure>


# Easy Look At

A c# component that allows you to quickly aim a Transform at another Transform

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FnEbLaCdx80J2ozZnS3QG%2Fimage.png?alt=media&amp;token=f3b52002-17f5-4677-b541-ae3c346500cd" alt="" width="334"><figcaption></figcaption></figure>

Rebuild in editor to get things posed how you want, or rebuild in Play mode if you want it to be dynamic.

LookTarget is a transform that you want to look at

Enable ScaleToTarget if you want this Transform to match the look targets Scale


# Easy Shake

A c# component that shakes a transform.

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FvLhD2I07hEXUwb4GuyNO%2Fimage.png?alt=media&amp;token=eb889151-ccbd-4ffe-b4dd-e1257d5d3307" alt="" width="324"><figcaption></figcaption></figure>

Can be used for Camera shakes or damage effects etc.&#x20;

* Shake Duration - How long to shake for ( < 0 for infinite)
* Shake On Enable - Auto start the shake on enable
* Movement Lerp Mod - Multiplier for the lerp delta that moves the Transform to the next shook position
* Movements Per Second - How often to find a new shake position
* Minimize Shake Over Time - Automatic falloff for the position and rotation offset as the duration approaches the end
* Max Position Offset - How big each shake position can be
* Max Rotation Offset Angles - How big of an angle each shake rotation can be
* Destroy Component On End - Destroy self after a shake is completed

Press the Shake button to simulate the shake in Editor

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FfZJBbatIZsZ9COJlai0b%2FEasyShakeDemo.gif?alt=media&amp;token=e537c3c8-c777-406c-a02c-dfbde5132409" alt="" width="375"><figcaption></figcaption></figure>


# Easy Destroy

A c# component that destroys or disables the GameObject it is on

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FII1sP3AsNzbsW0OIkSVB%2Fimage.png?alt=media&amp;token=04f2f0d0-0ba4-447e-8cf3-b6cb5a522ac2" alt="" width="301"><figcaption></figcaption></figure>

Attach to any GameObject you want destroyed or disabled after X seconds

{% hint style="info" %}
Useful for prefabs that are temporary, such as VFX. Just attach it to the prefab and it will destroy itself when its done with the effect.&#x20;
{% endhint %}


# Unity Asset Store

The [Unity Asset Store](https://assetstore.unity.com/) provides a lot of great resources for game development. You can import these into Airship games just like any other Unity project. However there are some things the will not work in Airship. Be sure to thoroughly read about the asset before purchasing. If you are unsure, you can reach out in [the Discord channel](https://discord.gg/WfdZtaTnWP) for advice.&#x20;

### Supported Assets

Most artwork will work in Airship. C# code does not work in Airship, unless it is solely for the Unity Editor. Any shaders / materials must be for URP (The Universal Render Pipeline)

A general rule of thumb:

* <mark style="color:green;">**Supported**</mark>
  * 2D / 3D Art
  * Animations
  * Sounds&#x20;
* <mark style="color:red;">**Will Not Work**</mark>
  * Code
  * Templates
* <mark style="color:yellow;">**Might Work**</mark>
  * Shaders
  * Tools

### Graphics

Shaders and Materials will need to support URP. All Unity assets will specify this in the overview. Look for the check mark.

<div align="left"><figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FyPFLZ4Ee8x4Ynb0QKvgT%2Fimage.png?alt=media&amp;token=0c428fea-cce2-44b3-a321-40940ed94f62" alt="" width="116"><figcaption></figcaption></figure></div>

### Animations

Animations can be imported and used in Airship games. If you use a custom character that supports Humanoid animations, there are many animations on the store that will work. However the Airship characters in the [character system](/characters/character-system) will not work with any animations from the asset store.&#x20;

{% hint style="danger" %}
Humanoid animations will not work for Airship Characters. Airship characters use a custom rig and require animations built specifically for it. To build animations for Airship characters you can use [this Blender file](/characters/character-animations/character-blender-animations)
{% endhint %}

### Code

No C# code can run during an Airship game. This means you can use tools in the Editor, but nothing at runtime.&#x20;

{% hint style="warning" %}
Even some art assets will contain C# code. Watch out for worlds like "Procedural", "Dynamic", and "Customizable" to see if they are doing things at runtime
{% endhint %}

{% hint style="warning" %}
Some editor time scripts still won't work in Airship if they rely on runtime scripts as well. For example a tool may let you customize a mesh in Editor, but then will require a C# component to lead the mesh you create. This would NOT work in Airship. But if it saves the mesh into your project for you to use normally, it WILL work in Airship.
{% endhint %}

You can view the Package Content to see if any scripts are included in the asset. Scripts in "Example" or "Sample" folders are usually safe since they aren't required for the core asset.&#x20;

<div align="left"><figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FenWsP1B9VDgw6tRmifPf%2Fimage.png?alt=media&amp;token=26d9656f-d7a7-4b2f-b50f-f9a107e04210" alt="" width="563"><figcaption></figcaption></figure></div>

### Optimization

Importing Unity Asset store packs is an easy way to bloat your project. Most assets will import at very large file sizes. Be sure to only include things you want to use, and to make sure the import settings are what you want.

{% hint style="warning" %}
Art asset packs can increase your game sizes by gigabytes! Optimize, and don't use any assets in your scenes / prefabs unless you want them in the download bundle for your game.&#x20;
{% endhint %}

For optimization tips [Look Here](/optimization/live-game-profiler).&#x20;


# Import a Package

Airship packages are bundles of assets that can be imported into your project. This allows reuse of code, artwork and sounds.

### Adding a package to your game

In Unity select `Airship > Airship` Packages which will open the Packages window

<div align="left"><figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FnLDry1iJKYB1dTxbjRxE%2Fimage.png?alt=media&amp;token=cf916db9-558a-484b-bdb2-55704c0209eb" alt="" width="176"><figcaption></figcaption></figure></div>

In the Packages window select the Add Package dropdown and enter the Package ID for the package you want to import

<div align="left"><figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FSG9gLd1w9nfIxAlhpTvC%2Fimage.png?alt=media&amp;token=01144c0f-e38c-43e6-a048-432392618bed" alt="" width="355"><figcaption></figcaption></figure></div>

Select Add Package and the assets will be imported into your project in the `Assets/AirshipPackages`folder

{% hint style="info" %}
The Package ID can be found on the [Airship Create](https://create.airship.gg/) website by navigating to the Packages page and selecting the package you want.
{% endhint %}


# Creating a Package

Airship packages are managed similar to games on the [Airship Create](https://create.airship.gg/) website.

### Create a new package

On the create website select Packages.

<div align="left"><figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FMB1Q4uwJscGFfYd582vp%2FScreenshot%202025-06-27%20164013.png?alt=media&amp;token=dce7b03d-ee31-4238-86ae-68211914310f" alt="" width="279"><figcaption></figcaption></figure></div>

Click the Create Package button and give it a name.

<div align="left"><figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FYD0d59enmpVCyrabG25O%2Fimage.png?alt=media&amp;token=949d574b-26c2-412a-bd0f-284b36e9f33a" alt="" width="259"><figcaption></figcaption></figure></div>

The path in the top left is what you will use to import the package into your game.

<div align="left"><figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FXnz3sO16vZssueCbcQaO%2Fimage.png?alt=media&amp;token=39a19731-23c8-436a-a260-653f11246630" alt="" width="182"><figcaption></figcaption></figure></div>


# Editing a Package

## Development Setup

Once you've created your package, go to an instance of Unity with Airship installed. To set up your package for development:

1. In the toolbar, go to Airship -> Airship Packages.
2. Click on the Create New Package section.
3. In the Package ID field, paste in the full Package ID from the website, e.g. `@YourOrg/PackageName`.
4. Click on Create Package.

This will create a new directory, e.g. `Assets/AirshipPackages/@YourOrg/PackageName`. Anything in this directory pertains to your package.

## First Publish

When you're ready to publish, go back to the Airship Packages window. Find your package and click Publish All. Do *not* click on Publish Code, as this will not work for the first publish.

## Subsequent Publishes

If the only changes to your package are code (TypeScript files), then you may use the Publish Code button. This is much quicker than Publish All.

If your changes contain non-code assets (e.g. an image), you must publish with Publish All, or else the publish may skip over your non-code asset changes.

## Using the Package

Your package is now ready to be used by yourself or anyone else. If you open another Airship project, you can include your new package by going to the Airship Packages window -> Add Package, and putting in the full name of your package. Clicking Add Package will then download the latest version of the package.

{% hint style="info" %}
If you use the package in the same game in which it's developed, then the game will always be using the local version of the package, *not* the published version. For this reason, it may be beneficial to have a separate project specifically for your package. This also gives you a dedicated project in which to test your package.
{% endhint %}


# Common Packages

The packages will be available via a browser in the future. For now you must know the exact Package ID of the package you wish to use. Here are a few recommended packages.

### Airship Packages

* [Core Package](/core-package/what-is-the-core-package) - Required materials and Typescript files used in all airship projects
* Core Materials - Materials and Shaders for all airship projects


# Character System

The character system is a way to easily manage entities in your game and attach them to Players. The bare bones system allows you to spawn characters on server and clients and connect to state events. It can also be used alongside other systems such as the [Movement System](/characters/character-movement-system), the Inventory System, and the Damage System.

Use the system in TS with `Airship.Characters`

```typescript
//Set the default prefab to use when spawning a character
Airship.Characters.SetDefaultCharacterPrefab(myCharacter);

//Listen to every new character spawn
Airship.Characters.ObserveCharacters((newCharacter) => {
    //Let the server and client sync
    newCharacter.WaitForInit();
    //Print their display name to the console
    print("Character Spawned: " + newCharacter.GetDisplayName());
})
```


# Spawning Characters

{% hint style="info" %}
For more details on how to control and customize characters see [The Character](/characters/character-system) section
{% endhint %}

You can spawn characters by calling `player.SpawnCharacter()` on the server.

Example: A component that spawns characters for all players joining the server.

```typescript
export default class CharacterSpawner extends AirshipBehaviour {
    public spawnTransform! = Transform;

    override Start() {
        Airship.players.ObservePlayers((player) => {
            player.SpawnCharacter(this.spawnTransform.position);
        });
    }
}
```

### Accessing Characters

You can access a player's character through `player.character`. This is avaliable on both the server and client.&#x20;

***

## Respawn Characters on Death

```typescript
import { Airship } from "@Easy/Core/Shared/Airship";
import Character from "@Easy/Core/Shared/Character/Character";
import { Game } from "@Easy/Core/Shared/Game";

export default class CharacterSpawner extends AirshipBehaviour {
	public spawnTransform!: Transform;

	override Start(): void {
		if (Game.IsServer()) {
			// Fired when players join the game
			Airship.players.ObservePlayers((player) => {
				player.SpawnCharacter(this.spawnTransform.position);
			});

			// Fired when a character dies
			Airship.damage.onDeath.Connect((damageInfo) => {
				const character = damageInfo.gameObject.GetAirshipComponent<Character>();
				if (character?.player) {
					character.player.SpawnCharacter(this.spawnTransform.position);
				}
			});
		}
	}
}

```


# Custom Character

Quickly get a custom character prefab working in your scene.

## Creating a Character Prefab

To create your game's character prefab you need to make a variant of the AirshipCharacter prefab.&#x20;

1. Right click in the project tab and choose `Create > Airship > Character Variant`
2. Double click the created prefab variant to make any changes

<div align="center"><figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FABWHpwCsWCcZG52LhXds%2FScreenshot%202025-07-25%20at%209.56.55%E2%80%AFAM.png?alt=media&amp;token=97a9b94c-4e82-41b1-97b8-7e437aff368c" alt="" width="375"><figcaption></figcaption></figure></div>

{% hint style="info" %}
You can add any graphics or components to this character to make it work for your game. There are also exposed variables on existing components. Some common changes would be to the [CharacterMovementData](/characters/character-movement-system) component or adding graphics to the NetworkedGraphicsHolder.&#x20;
{% endhint %}

## Spawning Your New Character Prefab

1. Find the `CharacterConfigSetup` component in your scene (it's there by default in template projects).&#x20;
2. Set the `Custom Character Prefab` field to your newly created prefab. This will cause characters to spawn using that prefab instead of the default AirshipCharacter prefab.

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2F9Rx4bcxUa0mGeu39LeCA%2FScreenshot%202025-07-25%20at%2010.01.27%E2%80%AFAM.png?alt=media&amp;token=05101ad1-8cf8-41d6-abc3-307d9bf3afcb" alt=""><figcaption></figcaption></figure>


# First Person Viewmodel

How to setup first person animations

## Forcing First Person Mode

Make the following changes on your `CharacterConfigSetup` component:

1. `Start In First Person = true`
2. `Character Camera Mode = Fixed`

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FYuaCeJALETqciFwCCU0z%2FScreenshot%202025-07-25%20at%2010.15.44%E2%80%AFAM.png?alt=media&amp;token=d509ba02-8bac-4acb-a01d-0dcd47492faf" alt="" width="375"><figcaption></figcaption></figure>

## Custom Viewmodel Arms & Animations

Airship spawns viewmodel arms by default but doesn't animate them at all. Here is how to create a variant of the default CharacterViewmodel arms and edit the animator:

1. Right click in project tab ⇒ Create ⇒ Airship ⇒ Viewmodel Variant
2. Double click the newly created prefab variant to open it
3. Replace the Animator Controller under `AirshipRig` with your own animator
4. Find your `CharacterConfigSetup` component and set the `Custom Viewmodel Prefab` field to your new prefab variant.

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2Fy9htBL2PYXoQKUnZv578%2FScreenshot%202025-07-25%20at%2010.19.52%E2%80%AFAM.png?alt=media&amp;token=c5cab8c2-776f-4f10-bd17-539bb237e884" alt="" width="375"><figcaption></figcaption></figure>

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FxeO8tukVZoRHrUhgZ9FM%2FScreenshot%202025-07-25%20at%2010.23.39%E2%80%AFAM.png?alt=media&amp;token=f5a1d7c7-36fd-48dd-914c-120f5626ed19" alt=""><figcaption></figcaption></figure>

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FiBJ0XVte5cEYDb38wCXN%2FScreenshot%202025-07-25%20at%2010.40.01%E2%80%AFAM.png?alt=media&amp;token=fc64693f-fc5f-409b-92e7-5597ea12bca3" alt="" width="375"><figcaption></figcaption></figure>

### Playing Animations

You can easily access the animator in code using:

```typescript
const animator = Airship.Characters.viewmodel?.anim;
if (animator) {
    animator.SetTrigger("Jump");
}
```


# Player System

Players are the connected users of your game. You have access to a Player object for every connection in the current server. Players can be connect to a spawned character but always exist regardless.

Access this API with `Airship.Players`

```typescript
//Get Local Player
const myLocalPlayer = Game.localPlayer;

//Listen to players that aren't your local player
const nonLocalPlayers: Player[] = [];
Airship.Players.ObservePlayers((newPlayer) => { 
    if(!newPlayer.IsLocalPlayer()){
        nonLocalPlayers.push(newPlayer);
    }
});

//Get a players username from their spawned character
Airship.Characters.ObserveCharacters((character) => {
    //Let the server and client sync their data
    character.WaitForInit();
    print("New character username: " + character.player?.username);
});

//Loop through all players and access their characters
for(const player of Airship.Players.GetPlayers()) {
    const character = player.character;
    if(character) {
        //This player has a spawned character
        ...
    }
}
```


# Character Movement System

How to work with Airships core character movement system

## Overview

When spawning in a default Character you get the benefit of several different movement features for your game.&#x20;

* **Jogging** - Default movement
* **Sprinting** - Faster movement
* **Crouching** - Slower movement with a lower hitbox
* **Jumping** - single or multi jump with controls for upward and downard force
* **Flying** - A no gravity mode for vertical movement (useful in debugging levels)
* **Step Ups** - Automatically step up to higher colliders smoothly
* **Slopes** - Control how fast slopes pull you down and what slopes you can move and jump on
* **Impulse** - Easily add forces to the character

The system is built with a Rigidbody and Box Collider. You can apply forces or directly override the velocity to add custom movement mechanics.

There are two main components for Movement. CharacterMovement which has all the logic for controlling movement, and CharacterMovementData which has all of the exposed variables for fine tuning your system.&#x20;

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FTx2AXhNKf5FsTcI1bPxL%2FAirshipCharacterMovement.gif?alt=media&amp;token=bbc61cab-d5ae-430a-b452-e8979ba1c24d" alt="" width="375"><figcaption></figcaption></figure>

## Setting Up Your Movement System

After creating your own Character prefab variant, you can customize the system as you see fit. Open up your Character prefab and scroll to the CharacterMovementData component in the inspector.&#x20;

{% hint style="info" %}
You can see a breakdown of the variables [On This Page](/characters/character-movement-system/character-movement-data)
{% endhint %}

## The Physics Setup

The character is controlled by a Rigidbody and Box Collider. The Box Collider is axis aligned. Meaning the root of your character DOES NOT ROTATE.&#x20;

The rotation happens purely on the graphical elements of the hierarchy. Specifically on the GraphicTransform of the movement class. So if you want to get the rotation of the character you will need to grab the rotation from that transform, or use the look vector from the CharacterMovement component

```typescript
//To get the characters rotation
character.movement.graphicTransform.rotation;

//To get the look vector of the character
character.movement.GetLookVector();
```

The rigibodies forces are controlled by the CharacterMovement component. If you want to add forces you can use the Impulse functions. If you want to control the velocity you can use the SetVelocity function.

```typescript
//Add an instant force to the characters rigidbody
character.movement.AddImpulse(Vector3.forward.mul(10));

//Stop all motion
character.movement.SetVelocity(Vector3.zero);
```

Its easy to check if another component has collided with the characters. Simply check for the Character component, or any other component on the root of the Character prefab.&#x20;

```typescript
import Character from "@Easy/Core/Shared/Character/Character";

export default class KnockbackCollider extends AirshipBehaviour {
    public knockbackForce: Vector3;

    protected OnTriggerEnter(collider: Collider): void {
        let character = collider.attachedRigidbody?.gameObject.GetAirshipComponent<Character>();
        if(character){
            //Interact with character
            character.movement.AddImpulse(this.knockbackForce);
        }
    }
}
```

## Animations

The animations of the characters movements will be automatically synced to the CharacterMovement state and networked to other players.


# Character Movement Hierarchy

The default AirshipCharacter prefab has a working setup for the movement system

The "AirshipCharacter" transform has the `CharacterMovement` and `CharacterMovementData` components on it for controlling your movement options. This root transform tracks the position of your character, but never rotates (to preserve an axis aligned collider). Access it in TS by grabbing the `RootTransform` variable.

The "NetworkedGraphicsHolder" is controlled by the movement code and always points towards the direction the character is trying to move towards. You can access it in TS by grabbing the `AirshipTransform` variable

The "AirshipRigHolder"  is the visible direction the character faces which is an interpolated value based on the characters desired direction and the camera angle.&#x20;

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FKSetRqHHqInMUcSoEaro%2Fimage.png?alt=media&amp;token=3936a5ca-b598-4466-abe2-eb792aaf6afe" alt="" width="563"><figcaption></figcaption></figure>

The "AirshipRig" transform holds the Animator for animating the character, as well as a Rig component that gives you reference to all of the bones of our avatars. You can access it in TS by grabbing the `rig` variable on the character.&#x20;

The children of the "AirshipRig" hold the visual elements of the character as well as the rig bone transforms

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2F4D6zkKqY9m8S0S2IfaAO%2Fimage.png?alt=media&amp;token=47d0aaa1-fa1e-41a3-bab2-dba3927d9061" alt=""><figcaption></figcaption></figure>


# Character Movement Physics

## The Physics Setup

The character is controlled by a Rigidbody and Box Collider. The Box Collider is axis aligned. Meaning the root of your character DOES NOT ROTATE.&#x20;

The rotation happens purely on the graphical elements of the hierarchy. Specifically on the NetworkedGraphicsHolder. So if you want to get the rotation of the character you will need to grab the rotation from that transform, or use the look vector from the CharacterMovement component

```typescript
//To get the characters rotation
character.movement.graphicTransform.rotation;

//To get the look vector of the character
character.movement.GetLookVector();
```

The rigibodies forces are controlled by the CharacterMovement component. If you want to add forces you can use the Impulse functions. If you want to control the velocity you can use the SetVelocity function.

```typescript
//Add an instant force to the characters rigidbody
character.movement.AddImpulse(Vector3.forward.mul(10));

//Stop all motion
character.movement.SetVelocity(Vector3.zero);
```

Its easy to check if another component has collided with the characters. Simply check for the Character component, or any other component on the root of the Character prefab.&#x20;

```typescript
import Character from "@Easy/Core/Shared/Character/Character";

export default class KnockbackCollider extends AirshipBehaviour {
    public knockbackForce: Vector3;

    protected OnTriggerEnter(collider: Collider): void {
        let character = collider.attachedRigidbody?.gameObject.GetAirshipComponent<Character>();
        if(character){
            //Interact with character
            character.movement.AddImpulse(this.knockbackForce);
        }
    }
}
```


# Character Movement Data

Details on the exposed variables on CharacterMovementData

### Size

Control the Box Collider of the character

<div align="left"><figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2Fdtl0XB8pMPpIjnZEDij3%2Fimage.png?alt=media&amp;token=8438daaf-a8d3-494e-aa36-4fd6cb4320d0" alt="" width="375"><figcaption></figcaption></figure></div>

**Height**  - controls the height of the bounding box

**Radius** - is the width and depth of the bounding box.

### Movement

core variables for moving the character

<div align="left"><figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2Fnq9fMwbjhxzwfYNsUyvi%2Fimage.png?alt=media&amp;token=a99a7b80-c68b-456c-b29d-d84fb11035c7" alt="" width="375"><figcaption></figcaption></figure></div>

**Use Acceleration Movement** - Toggle between Instant Motion and Acceleration Motion. Instant Motion drives the character instantly to the target speed. Acceleration Motion will move the character with a force over time.&#x20;

**Speed** - Desired speed to move while the character is jogging. Will instantly move to this in Instant Motion mode or stop the acceleration when it reaches this speed. In meters per second

**Sprint Speed** - Same as speed but while sprinting.

**Acceleration Force** - How fast to accelerate while in Acceleration Mode. Also controls acceleration when your character is moving faster than the target speed (ie. being flung into the air by a spring). In meters per second

**Sprint Acceleration Force** - same as Acceleration Force but while sprinting

**Min Acceleration Delta** - When moving faster than your target speed, your acceleration will be dampened if you try to acceleration in the direction you are moving. This value is a normalized minimum amount that you can move in a direction you are already moving.&#x20;

**Only Sprint Forward** - If checked, players will only be able to sprint if their velocity is moving forward

### Crouching

Specific modifiers for the crouching state

<div align="left"><figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FbwHEvyGwldqosf7ssmsv%2Fimage.png?alt=media&amp;token=1eae57b3-90ee-4d0f-a223-48a162b191d9" alt="" width="375"><figcaption></figcaption></figure></div>

Auto Crouch -&#x20;

Prevent Falling While Crouched -

Prevent Step Up While Crouched -

Crouch Speed Multiplier -

Crouch Height Multiplier -

### Jump

<div align="left"><figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FIRPdgOl0PEdvYkdKbTNr%2Fimage.png?alt=media&amp;token=8fb6cb80-7662-4d96-bc48-92e505834eda" alt="" width="375"><figcaption></figcaption></figure></div>

Number Of Jumps -

Jump Speed -

Jump Coyote Time -

### Flying

<div align="left"><figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FcE7DN0SIpozktusItZm6%2Fimage.png?alt=media&amp;token=fc05e886-c0d0-405c-b9b2-943cdfa07722" alt="" width="375"><figcaption></figcaption></figure></div>

Number of Jumps -&#x20;

Jump Speed -&#x20;

Jump Coyote Time -&#x20;

### Gravity

<div align="left"><figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FI3fghBUIe3CvaSEx6enC%2Fimage.png?alt=media&amp;token=5d1865dc-f913-4f73-8ba6-2b610a28154f" alt="" width="375"><figcaption></figcaption></figure></div>

Use Gravity -&#x20;

Use Gravity While Grounded -&#x20;

Gravity Multiplier -&#x20;

Upwards Gravity Multiplier -&#x20;

### Gravity

How gravity effects this character

<div align="left"><figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FMXflpkwlsA6kJtDWItPn%2Fimage.png?alt=media&amp;token=25fdf61e-dd3f-4d37-8efe-588b5120349e" alt="" width="375"><figcaption></figcaption></figure></div>

Use Gravity -&#x20;

Use Gravity While Grounded -&#x20;

Gravity Multiplier -&#x20;

Upwards Gravity Multiplier -&#x20;

### Physics

<div align="left"><figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2F0wwLjkJX40vWhYP7cVxn%2Fimage.png?alt=media&amp;token=734a15f3-8445-4e25-93e8-5115ca37f2a7" alt="" width="375"><figcaption></figcaption></figure></div>

Prevent Wall Clipping -&#x20;

Ground Collision Layer Mask -&#x20;

Terminal Velocity -&#x20;

Minimum Velocity -&#x20;

Use minimum Velocity In Air -&#x20;

Drag -&#x20;

Air Drag Multiplier -&#x20;

Air Speed Multiplier -&#x20;

### Step Ups

<div align="left"><figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2F65YsDCXcLBQIhnVT8V9w%2Fimage.png?alt=media&amp;token=c60c0cb4-142a-43dc-b562-68a29047d4e0" alt="" width="375"><figcaption></figcaption></figure></div>

Detect Step Ups

Always Step Up

Assisted Ledge Jump

Max Step Up Height

Step Up Ramp Distance&#x20;

Slopes

<div align="left"><figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2F8nK1Tmd8Wc7IFN7wPO0T%2Fimage.png?alt=media&amp;token=35be8876-1dcf-4e29-9df1-1ac8dfd79ed1" alt="" width="375"><figcaption></figcaption></figure></div>

Detect Slopes -&#x20;

Slope Force -&#x20;

Min Slope Delta -&#x20;

Max Slope Delta -&#x20;


# Character Movement Events

```typoscript
public enum CharacterState {
    Idle = 0,
    Running = 1,
    Airborne = 2,
    Sprinting = 3,
    Crouching = 4
}

/// <summary>
/// Called whenever the movement system enters a new CharacterState.
/// </summary>
public event StateChanged stateChanged;

public enum NetworkedStateSystemMode
{
    /** The system will be used as a way to generate commands to send to an authoritative server. */
    Input,

    /** The system is the authority. It will process commands either from itself, or a remote client. */
    Authority,

    /**
     * The system is an observer. It will only be provided snapshots and will need to interpolate between
     * them to display what has already happened.
     */
    Observer,
}

/// <summary>
/// Called when the type of NetworkedStateSystemMode is set.
/// </summary>
public event Action<object> OnSetMode;

/// <summary>
/// Called when a new command is being created. This can be used to set custom data for new
/// command by calling the SetCustomInputData function during this event.
/// </summary>
public event Action<object> OnCreateCommand;

/// <summary>
/// Called on the start of processing for a tick. The state passed in is the last state of the
/// movement system.
/// Params: CharacterMovementInput input, CharacterMovementState state, boolean isReplay
/// </summary>
public event Action<object, object, object> OnProcessCommand;

/// <summary>
/// Called at the end of processing for a tick. This is after the command has been processed by
/// the move function. Use this event if you want to modify the result of the tick. Remember:
/// the resulting state from the provided input must be deterministic. Failure to have deterministic
/// state will cause unwanted resimulations.
/// Params: CharacterMovementInput input, CharacterMovementState finalState, boolean isReplay
/// </summary>
public event Action<object, object, object> OnProcessedCommand;

/// <summary>
/// Called when the movement system needs to reset to a specific snapshot
/// state. The passed object is the state that we need to reset to.
/// </summary>
public event Action<object> OnSetSnapshot;

/// <summary>
/// Called when we need to capture a given snapshot.
/// </summary>
public event Action<object, object> OnCaptureSnapshot;

/// <summary>
/// Fired every frame. Provides lastState, nextState, and delta between the two.
/// Internally this is used to position the character in the correct location for rendering
/// based upon the received network snapshots.
/// </summary>
public event Action<object, object, object> OnInterpolateState;

/// <summary>
/// Fired on fixed update, but only when a new state has been reached. We use this internally
/// to set things like animation state where interpolation between two states is not possible.
/// Provides the new state that has been reached.
/// </summary>
public event Action<object> OnInterpolateReachedState;

public event Action<object, object> OnCompareSnapshots;

public event Action<object> OnMoveDirectionChanged;

/// <summary>
/// Called when the look vector is externally set
/// Params: Vector3 currentLookVector
/// </summary>
public event Action<object> OnNewLookVector;

/// <summary>
/// Called when movement processes a new jump
/// Params: Vector3 velocity
/// </summary>
public event Action<object> OnJumped;

/// <summary>
/// Params: Vector3 velocity, RaycastHit hitInfo
/// </summary>
public event Action<object, object> OnImpactWithGround;
```


# Character Movement Networking

The core multiplayer movement system supports Client Authoritative and Server Authoritative movement. The default movement networking mode is Client Authoritative.

### Client Authoritative

The client controls their own character and reports their position and state the server. The server sends the state information to all observers.  This is the default networking mode.

| PROS                                                       | CONS                                                         |
| ---------------------------------------------------------- | ------------------------------------------------------------ |
| <mark style="color:green;">Simple to implement</mark>      | <mark style="color:red;">Easy for bad actors to cheat</mark> |
| <mark style="color:green;">Low CPU and network cost</mark> |                                                              |

### Server Authoritative

The client sends inputs to the server and predicts what will happen. The server runs the inputs, and sends the correct results back to the client and all observers. If the servers result is different than the client, the client will replay all predicted inputs with the correct data.&#x20;

{% hint style="danger" %}
This is an advanced feature with strict requirements and will significantly increase the complexity of any movement and physics related game mechanics. For more information read [Server Authoritative Movement](/characters/character-movement-system/character-movement-networking/server-authoritative-movement).
{% endhint %}

| PROS                                                                                                      | CONS                                                            |
| --------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------- |
| <mark style="color:green;">Makes movement cheats impossible</mark>                                        | <mark style="color:red;">Complex implementation</mark>          |
| <mark style="color:green;">Server always has full control over clients and their state information</mark> | <mark style="color:red;">Higher CPU and Networking costs</mark> |


# Server Authoritative Movement

How to use Server Authoritative Movement.

{% hint style="danger" %}
Server authoritative movement is an advanced feature and will significantly increase the complexity of any movement related game mechanics. Unless your game has strong competitive integrity requirements, we recommend using Client Authoritative movement.
{% endhint %}

If you are not familiar with the concept of Server Authoritative movement, the [Source Multiplayer Networking](https://developer.valvesoftware.com/wiki/Source_Multiplayer_Networking) wiki has a good overview. Airship's server authoritative networking model closely follows the concepts explained there.

## Set Up

To use Server Authoritative networking, simply create a character variant and check the "Server Auth" checkbox in the "Character Networked State Manager" component.

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FA4beopFacaa1kl3dw26t%2Fimage.png?alt=media&amp;token=83599780-ea09-4370-b124-f3370b493058" alt=""><figcaption></figcaption></figure>

{% hint style="warning" %}
When server auth movement is enabled, the client may call Physics.Simulate() many times in one FixedUpdate step in order to resimulate incorrectly predicted commands. Use the AirshipOfflineRigidbody or AirshipNetworkedObject components to stop clients from incorrectly simulating rigidbodies that are not part of the character networking system.
{% endhint %}

## Command Prediction

When server authoritative movement is enabled, the client will generate input commands during fixed update and send these commands to the server. It will also run those commands locally to make movement commands appear instant.&#x20;

Periodically, the server sends the result of the most recently processed command back to the client. When the client receives a result from the server, it checks the result against its prediction. If the client was incorrect about the result of a command, it must replay all commands which have not been confirmed.

The client replays commands by resetting the state of the character back to the authoritative state provided by server. The client then runs all unconfirmed commands in order and updates the predicted result of each command.

## Modifying Movement Behavior

Any change to movement behavior must be predicted on both the client and server. For example, if your game has an item that launches you forward with an impulse when you click, you would need to perform this impulse at exactly the same time on both the client and server. If your client processes that impulse on command number 100, the server must also process that impulse when it receives command number 100.

We expose a system for hooking into all of the correct lifecycle events for implementing this behavior through the Predicted Command Manager in the Core package. Predicted Commands can include their own command data, state data, and custom processing logic.


# Architecture

An overview of how server authoritative character networking works and the associated tools you can use to modify the character behavior.

{% hint style="danger" %}
This documentation assumes you have knowledge of the basics of Server Authoritative Networking. Refer to the resources linked in [Server Authoritative Movement](/characters/character-movement-system/character-movement-networking/server-authoritative-movement) for background information.
{% endhint %}

## How Character Movement is Processed

Each tick, the client collects the input that the player has given. This input contains information like a move direction, if they want to jump, if they're holding sprint, etc. The client packages this input information into a "Command" and labels it with a command number. Each time the client generates a new command, it increments the command number. Every command that is generated is sent to the server for processing, but the client also predicts the result of the command by immediately processing the command locally.

Both the client and server use the same algorithm to update the position of the character. That means that with the same input command, the server and client *should* agree on the end result of the command.

In order for the client to check if its predicted result is the same as the server's result, the client stores a snapshot of the character's state after processing each command. The snapshot includes the command number of the last command processed. When the server finishes processing a command, the server also captures a snapshot. The server sends it's snapshot back to the client. Once the server's snapshot has been received, the client can check if it's predicted snapshot ended up being the same as the one the server generated.

If the server and client agree on the result of the command, then nothing happens. The client was correct, so all future commands based on that correct result should also hopefully be correct. However, if the result of processing a command is different on the client and server, the client needs to correct it's predictions. The client does this by resetting the character back to the authoritative snapshot the server provided. Once the character is reset, the client will replay all of the commands after the one that was mis-predicted. As it replays the commands, it overwrites the previous results for each command to generate a new predicted timeline.

## Including Custom Data and Logic in Character Movement Processing

{% hint style="info" %}
We provide the [Predicted Command Manager](/characters/character-movement-system/character-movement-networking/server-authoritative-movement/predicted-command-manager) as a framework for extending character movement behavior. The Predicted Command Manager takes care of connecting to the right functions at the right times and ensures that the correct code runs during replays. It is the recommended way to work with server authoritative character movement.
{% endhint %}

There are various extension points in the character movement process. Generally a combination of multiple connections to these extension points will be required to properly implement modifications to the character movement system.

### Event Diagram

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FX3xf1CWPjBFmv9Jkiyw4%2FCharacter_Movement_Events.png?alt=media&amp;token=bf5ccbf3-de41-40c3-8322-16e4bc8d8059" alt=""><figcaption></figcaption></figure>

### Notable Events

#### OnCompareSnapshots

This event fires on the client when a new snapshot arrives from the server. By default, the character networking logic doesn't know how to compare the custom data included in a snapshot. This event allows you to add additional comparison logic to the snapshot comparison when it occurs on the client. Use `character.SetComparisonResult()` to update the result for the snapshot when this event fires.

#### OnAddCustomInputData

This event fires when the character networking is generating a new command on the client. You can use `character.AddCustomInputData()` to add additional data to the command. This data will be made available in the `OnUseCustomInputData` event on both the client and server when the generated command is processed.&#x20;

#### OnUseCustomInputData

This event fires when the client or server is processing a command. You can use this event to make changes to the character movement logic based on the custom input data provided. It's important that all information required for your custom logic is included in the input or snapshot data, so that your results are deterministic.

#### OnAddCustomSnapshotData

This event fires when the client or server is creating a snapshot of the character's state. This snapshot is used to determine if the server and client agree on the final results of processing a command. You can use this event to encode additional data to use for comparison by calling `character.AddCustomSnapshotData()`.

#### OnInterpolateSnapshot

This event fires when an observed characters position is being updated for rendering. Observed characters are characters that your local client does not control, it must simply display the snapshots being received. Character interpolation looks at two snapshots and interpolates between them. You can use this function along with `OnInterpolateReachedSnapshot` to modify the rendering of observed characters.


# Predicted Command Manager

How to utilize the predicted command manager to easily create server authoritative commands with client prediction.

## Basic Concepts

The predicted command system allow you to create a set of logic and data that will be predicted on the client when using Server Authoritative character networking. For example, if you want to create an ability that launches the player in the air when activated, you would need to ensure that the server and client agree on when the ability was used, as well as ensure that both the client and server use the same logic to apply the force.

### Commands

Commands are a set of logic that will run as part of the character movement processing. To make a new command, you extend the `PredictedCommand` class. Commands should implement the `GetCommand()`, `OnTick()`, `OnCaptureSnapshot()`, `ResetToSnapshot()`, and `CompareSnapshots()` functions. Do not yield in any of the predicted command functions.

#### Predicted Command Manager

The `PredictedCommandManager` is a singleton running on both the client and server. The manager handles starting new commands and ensuring the proper execution of running commands. The `PredictedCommandManager` can get information about which commands are running for a character, validate which commands should run, and provides command related signals such as when a command stops running.

## Example

The following example implementation is an ability which impulses your character upwards after charging for a short amount of time. While the command is charging, the character will move slowly.

### Command

{% code title="TestPredictedCommand.ts" fullWidth="true" %}

```typescript
import { Keyboard } from "../../UserInput";
import PredictedCustomCommand from "./PredictedCustomCommand";

// The input data for this command. This is added to every character input command.
// We use arrays for these since it's less data to send over the network
type InputCommand = [charging: boolean, completed: boolean];

// The state data associated with this command. We network the progress so that if the client and
// server disagree on how much progress has been made, the client will reconcile to use the server
// progress.
type StateData = [progress: number];

// We define our predicted command by extending PredictedCustomCommand and passing in our data types.
// We will register this predicted command with the PredictedCommandManager later. Keeping mind, this is
// NOT an AirshipBehavior. You don't need to add it to a game object.
export class TestPredictedCommand extends PredictedCustomCommand<InputCommand, StateData> {
	// state
	private progress = 0; // How far along we are in the charge process.
	private completed = false;

	// constants
	private CHARGE_TIME_SEC = 1; // How long we want to charge for. 

        // This function is called every time a new instance of this command is created. On replays, this command
        // might be destroyed and recreated many time. Keep that in mind since any state you include (like progress
        // above) will be reset. ResetToSnapshot is always called after Create(), so you should load any state you
        // need from the snapshot there.
	Create(): void {
		// Slow the character movement speed down while this command is running.
		this.character.movement.movementSettings.speed *= 0.1;
	}

	Destroy(): void {
		// Reset the character movement speed back to normal when it ends.
		this.character.movement.movementSettings.speed /= 0.1;
	}

	// Called when the client is generating a new command. This is where you collect any data you
	// need to process in OnTick(). Remember that this is being generated on the client, so you should
	// pass things like input here.
	GetCommand(): false | InputCommand {
		// If the player is holding down the ability button, we continue to charge the ability.
		if (Airship.Input.IsDown("Ability")) {
			return [true]; // Send true since the ability is being held down.
		}
		return false; // If the ability is not being held down, we just exit the command commpletely by returning false.
	}

	// Runs on both the client and the server either before (default) or after character movement is processed depending
	// on the configuration provided when registering the command with the PredictedCommandManager. We can access
	// the data we generated in GetCommand() and perform our logic based on that data.
	override OnTick(input: Readonly<InputCommand> | undefined, replay: boolean, fullInput: CharacterInputData) {
		if (!input) return false;

		this.progress++;

		if (this.progress >= this.CHARGE_TIME_SEC / Time.fixedDeltaTime) {
			this.character.movement.AddImpulse(Vector3.up.normalized.mul(20));
			this.completed = true;
			return false;
		}
	}

	// This runs after OnTick() and after the physics simulation completes. Here we return the progress data since that's
	// what we want to make sure stays in sync between the client and server.
	OnCaptureSnapshot(): StateData {
		return [this.progress, this.completed];
	}

	// This function gets called whenever there's a mismatch between the client and server. It may also get called
	// if the client replays or if the server is processing lag compensation. The purpose of this function is to
	// reset the state of this command to match whatever snapshot is provided to it.
	ResetToSnapshot(state: Readonly<StateData>): void {
		this.progress = state[0];
		this.completed = state[1];
	}

	// Called whenever the client needs to compare it's local predicted result to the actual result provided by the server.
	// We want to ensure that the state data we have locally actually matches the state data returned by the server.
	CompareSnapshots(a: Readonly<StateData>, b: Readonly<StateData>): boolean {
		if (a[0] !== b[0]) return false; // If it doesn't match, then we return false
		if (a[1] !== b[1]) return false;
		return true; // If it matches we are good!
	}
}

```

{% endcode %}

### Registering the Command

To register a command, you need to call `PredictedCommandManager.Get().RegisterCommands()`.  You can call `RegisterCommands()` multiple times if needed. The command needs to be registered on both the client and the server for it to work. Here's a manager singleton that registers the command, and sets up the other configuration needed to actually use our test command.

{% code title="TestCommandManager.ts" fullWidth="true" %}

```typescript
import { Airship } from "@Easy/Core/Shared/Airship";
import { Game } from "@Easy/Core/Shared/Game";
import { Binding } from "@Easy/Core/Shared/Input/Binding";
import PredictedCommandManager, {
	CommandInstanceIdentifier,
} from "@Easy/Core/Shared/Network/PredictedCommands/PredictedCommandManager";
import { TestPredictedCommand } from "@Easy/Core/Shared/Network/PredictedCommands/Test";

export default class TestCommandManager extends AirshipSingleton {
	// Constants
	private CMD_IDENTIFIER = "cmd"; // Identifier for the command. Can be anything, just needs to be unique
	private CMD_COOLDOWN_SEC = 3; // Cooldown for the ability
	private CMD_ACTION_NAME = "Ability"; // The ability action name (This is for user input)

	// Cooldown tracking
	private canUseAt = new Map<number, number>(); // Map of when a character can use their ability again. We use a map because the server
						      // has to track all of the players cooldowns.

	// Client only local command tracking
	private localCommand: CommandInstanceIdentifier | undefined; // Used only for tracking the running command on the local client.

	override Start(): void {
		// Registers the command with the predicted command manager. This allows us to run the command using the provided
		// identifier.
		PredictedCommandManager.Get().RegisterCommands({
			[this.CMD_IDENTIFIER]: {
				handler: TestPredictedCommand,
			},
		});

		// Validate that the command should be able to run. This runs on both the client and server.
		PredictedCommandManager.Get().onValidateCommand.Connect((event) => {
			// This even fires for all commands that start, so make sure we only run these checks
			// on our specific command identifier.
			if (event.commandId !== this.CMD_IDENTIFIER) return;
			// Get the next time the player should be able to run this command.
			const nextUseTime = this.canUseAt.get(event.character.id) ?? 0;
			// If the players ability is on cooldown, then we set the event to cancelled. This stops the command
			// from running.
			if (nextUseTime > Time.time) {
				event.SetCancelled(true);
				return;
			}
		});

		// This event fires when the command ends authoritatively, meaning when this event fires, the server has confirmed
		// the that command ended, and we shouldn't see it be ticked again (although it could still run during resimulations!).
		PredictedCommandManager.Get().onCommandEnded.Connect((command, result) => {
			// The finalState is the last snapshot that was captured on the tick the command ended. We use this to decide
			// if the ability was actually used. Remember that our ability has a charge up time, and we don't want to
			// reset the cooldown unless they actually got launched in the air.
			const finalState = result as [progress: number, completed: boolean];
			if (finalState && finalState[1] === true) { // Check if the "completed" state was true
				// Set the next time the player can use this ability in our cooldown tracking map.
				this.canUseAt.set(command.characterId, Time.time + this.CMD_COOLDOWN_SEC);
			}
		});

		// Observe all the characters in the game.
		Airship.Characters.ObserveCharacters((character) => {
			// The returned function is called when the character despawns.
			return () => {
				// Remove any cooldowns for characters which are despawned. This avoids memory leaks!
				this.canUseAt.delete(character.id);
			};
		});
		
		if (Game.IsClient()) {
			// Create an action for our input.
			Airship.Input.CreateAction(this.CMD_ACTION_NAME, Binding.Key(Key.Q));
			// Listen to when the action button is pressed.
			Airship.Input.OnDown(this.CMD_ACTION_NAME).Connect(() => {
				// If we are running the ability, then we don't want to start another one.
				if (
					this.localCommand &&
					// The last two parameters are checking if the command is queued, meaning it will run next tick,
					// and checking if the command used to be running, but we don't know if it's officially ended yet.
					// It's important to include those parameters in this case because we can't run the ability twice,
					// and we wouldn't want to start running the ability again before we know if it's ended.
					PredictedCommandManager.Get().IsCommandInstanceActive(this.localCommand, true, true)
				) {
					// Ignore the input if the command is already running.
					return;
				}
				// If the command isn't running, we run the command!
				this.localCommand = PredictedCommandManager.Get().RunCommand(this.CMD_IDENTIFIER);
			});
		}
	}
}

```

{% endcode %}


# Lag Compensation

Performing lag compensated checks using Airship's Character Networking.

{% hint style="warning" %}
This is an advanced topic. Most games do not need lag compensation, basic checks can be enough. Lag Compensation is best used in places where your game has strong competitive integrity requirements.
{% endhint %}

## Background

If you're not familiar with the concept of lag compensation, Valve's [Source Multiplayer Networking](https://developer.valvesoftware.com/wiki/Source_Multiplayer_Networking#Lag_compensation) wiki is a good place to start. Valve's wiki talks about lag compensation in terms of server authoritative networking, but Airship's Lag Compensation works with both server authoritative and client authoritative models.

## Example

{% code fullWidth="true" %}

```typescript
// You submit lag compensation checks for processing by calling the LagCompensationCheck function on a Player object. This can only
// be called on the server. It's important that you do not yield in the passed functions.
this.character.player?.LagCompensationCheck(
	// The first parameter is the check function. The check function will run after the position of each player has been
	// updated to reflect the position the client saw.
	// This check function should NOT modify the world, it should only read the positions of player and perform raycast checks.
	// If you make changes to the position or velocity of players, it will be overwritten.
	() => {
		// Do a raycast hit check.
		const [hit, position, normal, collider] = Physics.Raycast(
			this.character.movement
				.GetPosition()
				.add(new Vector3(0, 1.5, 0)),
			this.character.movement.GetLookVector(),
			WEAPON_RAYCAST_DISTANCE,
			this.hitLayers,
		);
		// Pass the results to the processing function
		return { hit, position, normal, collider };
	},
	// The second parameter is the processing function. You can process the result of the check here. This function runs
	// with the latest state of the world, so it is safe to modify positions, apply forces, etc.
	({ hit, position, normal, collider }) => {
		// If there was no hit, return
		if (!hit) return;
		// Get the character we hit.
		const hitChar = collider.gameObject.GetAirshipComponentInParent<Character>();
		// If there was no character, return.
		if (!hitChar) return;
		// Inflict damage on the character we hit.
		hitChar.InflictDamage(10, this.character.gameObject);
		hitChar.movement.AddImpulse(new Vector3(0, 20, 0));
	},
);
```

{% endcode %}

## Airship Networked Object

The AirshipNetworkedObject component can be placed on any game object with a Rigidbody to ensure that it is also moved to the correct position during Lag Compensation requests. Any objects that don't have this component will be untouched.


# Character Camera

The Character System includes an API for interacting with the Camera.  It can be accessed via `Airship.Camera`

{% hint style="info" %}
This API is only relevant if you are using the Airship Character System. If you are using your own character system, you can just update the camera transform directly as you normally would in Unity.&#x20;
{% endhint %}

### Changing Camera Modes

Switching between Fixed and Orbit camera modes is the most common. By default characters use Fixed camera mode.&#x20;

```typescript
// Enter orbit camera mode
Airship.Camera.SetMode(CharacterCameraMode.Orbit);

// Enter fixed camera mode
Airship.Camera.SetMode(CharacterCameraMode.Fixed);
```

For more complex and custom camera setups, see the [Default Camera Modes](broken://pages/CNQXfA2zDO6QFKut3w0z) and [Camera Structure](/characters/character-camera/custom-camera-mode) pages.

### First Person

You can use the Camera manager to modify and listen to first person mode. Both orbit and fixed camera modes support first person.

```typescript
// Specify first person or not
Airship.Camera.SetFirstPerson(true);

// Toggle on and off first person
Airship.Camera.ToggleFirstPerson();

// Listen to first person changes
Airship.Camera.ObserveFirstPerson((isFirstPerson) => {
    print("First person: " + isFirstPerson);
})
```

{% content-ref url="/spaces/IbaXflSJA8L9N9yOx089/pages/mMvBmZWnFOzExMnxLGN2" %}
[Custom Camera Mode](/characters/character-camera/custom-camera-mode)
{% endcontent-ref %}

{% content-ref url="/spaces/IbaXflSJA8L9N9yOx089/pages/CNQXfA2zDO6QFKut3w0z" %}
[Broken mention](broken://spaces/IbaXflSJA8L9N9yOx089/pages/CNQXfA2zDO6QFKut3w0z)
{% endcontent-ref %}


# Custom Camera Mode

The camera functionality has been created in such a way to be agnostic to the game it is in. The top-level class for the camera is the `CameraSystem`. Only one instance of this class should be created, and a Unity `Camera` component must be passed to its constructor.

The whole camera system is written in TypeScript.

## CameraMode

The `CameraSystem` works by attaching `CameraModes` to it. A `CameraMode` is a simple interface that contains basic methods like `OnLateUpdate`. These methods are responsible for calculating the position and rotation of the camera in world-space. The `OnLateUpdate` function must return a `CameraTransform`, which is a simple object that contains a position Vector3 and rotation Quaternion.

Here is an empty `CameraMode`, not yet implemented:

```typescript
class MyCameraMode implements CameraMode {
    // OnStart is called by the camera system when the mode begins.
    OnStart(camera: Camera): void {}
    
    // OnStop is called when the camera system stops this mode.
    OnStop(): void {}
    
    // OnUpdate is called during Unity's Update stage.
    // This method is useful for handling user input, and sets itself
    // at LOWEST priority on the connection, to attempt to run after
    // any other Update code has run in the game.
    OnUpdate(deltaTime: number): void {}
    
    // OnLateUpdate is called during Unity's LateUpdate stage.
    // This method must return a CameraTransform, representing the
    // camera's position and rotation. This method sets itself at
    // the HIGHEST priority on the connection, attempting to run
    // first in the LateUpdate stage before anything else.
    OnLateUpdate(deltaTime: number): CameraTransform {}
    
    // This method is called right after the Unity camera's transform has
    // been set with the data from OnLateUpdate. This might be useful if
    // other custom transforms need to be added onto the camera outside of
    // just returning a position and rotation in OnLateUpdate.
    OnPostUpdate(camera: Camera): void {}
}
```

Here is an example of a custom `CameraMode` class that spins the camera:

```typescript
class MyCameraMode implements CameraMode {
    private spinAngle = 0;
    
    constructor(private readonly spinSpeed = 3) {}
    
    OnLateUpdate(deltaTime: number) {
        // Calculate spin angle:
        this.spinAngle = (this.spinAngle + deltaTime * this.spinSpeed) % 360;
        
        // Create the Vector3 and Quaternion representing the camera in 3D space:
        const position = new Vector3(0, 0, 0);
        const rotation = Quaternion.euler(0, this.spinAngle, 0);
        
        // Create the CameraTransform, which the CameraSystem will use to set the
        // transform of the Unity camera:
        return new CameraTransform(position, rotation);
    }
    
    OnStart(camera: Camera) {}
    OnStop() {}
    OnUpdate() {}
    OnPostUpdate(camera: Camera) {}
}
```

### Running a CameraMode

In order to run a camera mode, instantiate an instance of the camera mode and set it on the `CameraSystem`:

```typescript
cameraSystem.SetMode(new MyCameraMode());
```

If the CameraSystem is exposed through a CameraController, then the full code might look more like this:

```typescript
cameraController.cameraSystem.SetMode(new MyCameraMode());
```

### Stopping a CameraMode

There are two ways to stop a `CameraMode`.

1. Set a new `CameraMode` (this will stop the current one)
2. Clear the `CameraMode` (via `cameraSystem.ClearMode()`)

### Default Mode

This logic above for clearing the `CameraMode` has a problem. Let's say the player comes up to a shop, and the camera needs to switch to a static `CameraMode` that shows the player interacting with the shop. To do this, we simply set the new camera mode. However, what happens when the shop interaction ends? We stopped the old camera mode by setting the new one, so we can't get the old one back.

In order to solve this, we can set up a default camera mode by binding a callback function to run when the camera mode gets cleared. Any time the `ClearMode()` method gets called (*or* if no mode has yet to be set in the game), our callback will be called, which must return a camera mode.

For example, if we wanted our spinning camera to be the default camera mode for the game, we could write the following code:

```typescript
cameraSystem.SetOnClearCallback(() => {
    return new MyCameraMode();
});
```

Now, anytime that `cameraSystem.ClearMode()` is called, our callback will run and immediately set the new mode to our custom camera mode. In an actual game, this would probably default to a camera mode that attaches to the character.

## Field Of View

The camera's field-of-view (aka FOV) represents the vertical view angle in degrees. This field can be set using `cameraSystem.SetFOV(fieldOfView)`. The CameraSystem uses a spring effect to smoothly interpolate between field-of-views. So by default, a smooth (but quick) animation between the current FOV and the new FOV will run when `SetFOV` is called. If no amination is desired, a second parameter flag can be set to `true` to represent an immediate FOV change.

```typescript
// Zoom in when right-clicking:
mouse.RightDown.Connect(() => {
    cameraSysem.SetFOV(30);
});
mouse.RightUp.Connect(() => {
    cameraSystem.SetFOV(60);
});

// Same thing, but immediate (no animation/spring effect):
mouse.RightDown.Connect(() => {
    cameraSysem.SetFOV(30, true);
});
mouse.RightUp.Connect(() => {
    cameraSystem.SetFOV(60, true);
});
```

## Input Control Responsibility

The `CameraSystem` is not responsible for handling user input to control the camera. It is up to the implementation of each `CameraMode` to handle user input. These controls should take into consideration the following items:

## Performance Responsibility

It is the responsibility of each implemented `CameraMode` to perform well. Consider the fact that methods like `OnUpdate` and `OnLateUpdate` will be running every frame, and so heavy operations could have an impact on performance. Use the profiler to test code performance.


# Character Animations

## Core Animations

Airship Core has existing animations for jogging, sprinting, jumping etc. They will automatically be used on your characters but you can also customize and play your own animations.&#x20;

**There are two classes to help you control animations**

Character Animation Helper (A C# class)

Character Animator (A TS class)

{% hint style="info" %}
**Why are there two animation classes?** We need a C# to directly access some of Unity's animation features, as well as for more optimized calls that happen every frame. But we also need to capture and use data in Typescript.
{% endhint %}

***

## Animation Overrides

To play an animation on top of the core system you can use the override functions

You can play custom animations using `character.animationHelper.PlayAnimation`

```typescript
public animClip?: AnimationClip;
...
if(this.animClip){
    //Play anim clip on Override Layer 1 with a transition time of .1 seconds
    this.character.animationHelper.PlayAnimation(this.animClip, CharacterAnimationLayer.OVERRIDE_1, 0.1);
}
```

You can also replace the core animations by using an AnimationOverride asset. This allows you to drag and drop AnimationClips for specific actions without any code.

1. Copy and paste the default AnimationOverride object into your project folder

   *"Assets/AirshipPackages/@Easy/Core/Prefabs/Character/Animations/AirshipCharacterOverrider.overrideController"*
2. In your Character prefab variant, set the animators controller to be your override asset
3. Replace any default animation clips with your custom movement animation clips on your override controller

   <figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FHFP37eF0H7vDwacult9q%2Fimage.png?alt=media&amp;token=47ad7dd9-455c-4409-9815-087e6dd1be11" alt=""><figcaption></figcaption></figure>

## Character Animation Events

Characters by default use the AnimationEventListener component to listen to animation events. You can read more about the system on the [Animation Events Page](/unity-for-airship/animation-events).

To easily listen to character animation events in Typescript, connect to the OnAnimationEvent Signal on Character.animation:

```typescript
this.character.animation.OnAnimationEvent.Connect((key)=>{
    if(key === "MyAnimationEvent"){
        //Do Stuff
    }
});
```

***

## Creating New Character Animations

Animations built for the Character must match the Characters Ri&#x67;**.** The easiest way to animate for the character in Unity is to drag the CharacterAnimationDummy into your scene. This gives you bone gizmos and access to the animator at the root. Then you can use the Animation window to edit keys.

{% hint style="info" %}
You can also [Create Animations From Blender](/characters/character-animations/character-blender-animations) by downloading our character rig animation file. You will need to setup actions for each animation and export them to an FBX file which can be brought into your Unity project.
{% endhint %}

1. Create a new AnimationClip in your project and name it
2. Bring the animation dummy prefab in to your scene

   *"Assets/AirshipPackages/@Easy/Core/Prefabs/Character/CharacterAnimationDummy.prefab"*
3. On the root object add your animation clip reference to the Animation component

   <figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FpimL3jWlxISbFVCF2fNy%2Fimage.png?alt=media&amp;token=3660c427-7413-4fc4-b169-0a92d2ae667a" alt="" width="291"><figcaption></figcaption></figure>
4. Open the Animation window and you can now select and edit your animation clip. Use the record button to auto generate keys as you move the characters rig.

   <figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FZztV1SNQDL1HbSbwnvue%2Fimage.png?alt=media&amp;token=adef5afa-f83e-4b9e-9fb1-dcd6331ca891" alt="" width="375"><figcaption></figcaption></figure>

{% hint style="info" %}
The Airship Character prefab is used for third person views.&#x20;

The Character View model prefab is for first person.
{% endhint %}


# Character Rig Download

This page contains a download of the Airship Character Rig so you can animate in tools like Blender.

{% file src="/files/ZIGHnhiFvFN3W3Z6Ugi7" %}

{% hint style="info" %}
We use [Blender 3.5](https://download.blender.org/release/Blender3.5/) internally and recommend that version.
{% endhint %}

## Creating Animations With Blender

![](https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FN7X8kQFTn1YDsTmjTQVG%2Fimage.png?alt=media\&token=b7d64a96-eea5-466a-a95e-1ff7bc55da13)

You can create multiple animations in 1 blender file

* Open the Dope Sheet window
* Switch the dope sheet to the Actions panel
* Create a new Action
* Each action will export as an individual Animation Clip for Unity

<div align="left"><figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FNnjxLEoLGsVjiGkUjigi%2Fimage.png?alt=media&amp;token=95420129-1cc0-420d-8409-4e97cb2ad401" alt="" width="375"><figcaption></figcaption></figure></div>

### Exporting to FBX

Convert your animations to FBX to bring them into Unity

* File -> Export -> FBX
* Setup our recommended settings
* Save

{% hint style="success" %}
You can save your settings a preset for quick setup next time.

Click the + icon on the top right of the export window.
{% endhint %}

<div align="left"><figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FecHwSrP2a0R6oVOl77eN%2Fimage.png?alt=media&amp;token=8c2968bd-c470-4d7c-8179-1fc3c9bd2f7e" alt="" width="379"><figcaption></figcaption></figure></div>

### Importing to Unity

Place the FBX into a folder in your project or drag it into the Project window of Unity.&#x20;

Set the rig type to Generic and assign the character avatar

<div align="left"><figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FC74bZvzyQY5Vpka04Ja8%2Fimage.png?alt=media&amp;token=90ac6d49-fdc5-4275-8b28-ea97cc426d15" alt="" width="563"><figcaption></figcaption></figure></div>

You should see each Action you made as an Animation Clip in the Animation tab of your file

<div align="left"><figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2Fye7nJcCIx3bIOA5NUfGa%2Fimage.png?alt=media&amp;token=5a3b6370-0c33-4cd9-81b8-08a0a008162b" alt="" width="563"><figcaption></figcaption></figure></div>

Your animation clips can now be used as variables in AirshipComponents or directly in an Animator state machine.&#x20;

<div align="left"><figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2Fg5RlBjCjE1Ooc4P6Wz0h%2Fimage.png?alt=media&amp;token=bf88ab92-82ba-41d8-b75b-71704456509b" alt=""><figcaption></figcaption></figure></div>

```typescript
import Character from "@Easy/Core/Shared/Character/Character";

export default class AnimTest extends AirshipBehaviour {
	//Reference to the project file
	public animClip: AnimationClip;

	//Reference to the scene instance
	public character: Character;

	override Start(): void {
		//Play the animation on the character
		this.character.animationHelper.PlayAnimation(this.animClip, CharacterAnimationLayer.OVERRIDE_4, 0.5);
	}
}
```

<div align="left"><figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FeixyPb9LE4usPVVrWOm6%2Fimage.png?alt=media&amp;token=44edb609-549f-43e0-ad39-082cc6f8d581" alt="" width="375"><figcaption></figcaption></figure></div>


# Character Ragdoll

Quick toggling of ragdoll physics for characters

If you wish to be able to trigger ragdoll effects on your characters, be sure to make a variant of the prefab AirshipCharacterRagdoll, which has RigidBodies setup for ragdoll effects.

If your character prefab has a ragdoll on it, you can access it in TS by getting a reference to the CharacterRagdoll Airship component on the character rig. This component also has easy functions for adding forces to all of the ragdoll joints at once.

```typescript
const ragdoll = this.gameObject.GetAirshipComponent<CharacterRagdoll>();
if (ragdoll) {
	ragdoll.SetRagdoll(true);
	ragdoll.AddExplosiveForce(
		80, // Force value
		ragdoll.transform.position, // Explosion center point
		3, // Explosion radius
		0.25, // Upwards force modifier
		ForceMode.Impulse,
	);
}
```

### OnDeath Example

A common pattern is to enable a character's ragdoll when the character dies. This is a trivial task using the `Airship.Damage` singleton. Let's create a `RagdollManager` singleton. Remember to attach this component to a GameObject in the scene so that it starts up by itself.

```typescript
import { Airship } from "@Easy/Core/Shared/Airship";
import { DamageInfo } from "@Easy/Core/Shared/Damage/DamageInfo";
import CharacterRagdoll from "@Easy/Core/Shared/Character/Animation/CharacterRagdoll";

export default class RagdollManager extends AirshipSingleton {
	@Client()
	protected Start() {
		// Fetch ragdoll component on death and hand it off to the EnableRagdoll function
		Airship.Damage.onDeath.Connect((damageInfo) => {
			const character = damageInfo.gameObject.GetAirshipComponent<Character>();
			const ragdoll = character?.rig.gameObject.GetAirshipComponent<CharacterRagdoll>();
			if (ragdoll) {
				this.EnableRagdoll(damageInfo, ragdoll);
			}
		});
	}

	private EnableRagdoll(damageInfo: DamageInfo, ragdoll: CharacterRagdoll) {
		ragdoll.SetRagdoll(true);
		
		// Add other effects here as desired, e.g. ragdoll.AddExplosiveForce()
	}
}
```

{% hint style="info" %}
The ragdoll effect needs to run on the client, so we will use the `@Client()` decorator on our Start lifecycle method to ensure this code only runs on the client.
{% endhint %}


# Accessories Intro

Accessories are objects that attach to Airship Characters.

Accessories can be attached to the character by their bones (Rigid) or by weight painting (Skinned) . These could be clothing, face decals, weapons etc.&#x20;

Players customize their accessories through the Avatar editor, but each game can also overwrite characters accessories.

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FtXU1xFqkDHRi8us4qpCh%2FScreenshot%202024-09-05%20at%201.21.33%E2%80%AFPM.png?alt=media&amp;token=8f1ec306-dc83-4b95-9326-0025d730021e" alt=""><figcaption></figcaption></figure>

Characters have pre defined slots, and each slot can only have 1 accessory at a time. For example if your game forces a hat on a character, the players avatar hat will disappear and be replaced. The current slots can be seen in the dropdown on AccessoryComponent

<figure><img src="https://214663474-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIbaXflSJA8L9N9yOx089%2Fuploads%2FpUDaw8HOslwAkQXgQT8i%2Fimage.png?alt=media&amp;token=b4fbda6c-0da6-46c2-8c97-a8358e7d69c3" alt=""><figcaption></figcaption></figure>




---

[Next Page](https://docs.airship.gg/llms-full.txt/1)

