Room Definition Reference
In stateMachine rooms, the rules (GSL) registered with GS2-StateMachine run inside the room to create and update shared objects, validate operations, and handle the passage of time. This page summarizes the specifications for writing those rules.
The basic approach is to write rules in C# and generate GSL. If you build your game with Godot, you can also write them in GDScript (Writing Rules in GDScript). The C# definition format (state records, Step, and so on) is shared with StateMachine, so also see the C# Definition Reference. To try the whole procedure, see the Tutorial; for ticks and prediction, see the Rollback Sync Tutorial.
Rules Overview
| Target | Where it lives | Examples |
|---|---|---|
| Rules | GS2-StateMachine’s StateMachineMaster (versioned) | Spawning enemies, validating attacks, reviving |
| Room progress state | The rules’ state record. Not delivered to clients | Floor number, enemy object IDs |
| Shared values | Shared objects. Delivered to all participants | Position, HP, boss phase |
| Display | Unity GameObjects | HP bar, position interpolation |
The room state and shared objects are kept only while the room is running. They are lost when the room ends and are not persisted.
Writing in C#
In the rules class, write the following methods (only Start is required).
| Method | When it is called |
|---|---|
public static Step Start() | Once, when the room starts |
public static Step Interact(TState state, int objectId, int method) | When a player sends SharedObject.Interact(method) |
public static Step Timer(TState state, int objectId, int eventId) | When the time scheduled with Room.After arrives |
public static Step Tick(TState state, int tick) | At the rate set with DefineTickRate (ticks) |
public static Step Spawned(TState state, int objectId) | Right after a player spawns their own object (respond to spawns) |
In Start, define the kinds of shared objects, spawn the initial objects, and wait for input with Step.WaitFor(nameof(Interact), state).Or(nameof(Timer)). After processing, Interact and Timer keep waiting for the same input with Step.Stay(state).
Interact is the only operation players can send. Distinguish kinds of operations by the value of method. Adding public methods in C# does not make them callable from clients.
In the generation settings, specify RealtimeRoomV1 for hostProfile. With this profile, GameRewards (rewards) and GameRandom are not available. Draw random numbers with Room.Random.
Compile-Time Checks and Output for Unity
- A room calls only
Interact,Timer,TickandSpawned. Any other public Step method (including typos such asOnTick) and a reserved method that noStep.WaitForreachable fromStartincludes are compile errors (a handler that waits only for itself is never called). - The error enum (the third type of
Step) shares the result code of a refusal with the room’sCommandResult(0 to 99). Values below 100 are allowed only to reuse a room result by its name (such asInvalidOperation = 5); number the rules’ own codes from 100.RoomResultslists the room’s results: writeInvalidOperation = RoomResults.InvalidOperationorDefeated = RoomResults.FirstRulesCode.AlreadyApplied(6) reads as success on clients (RequestStatus.Succeeded): use it only for repeats of what already happened (opening an open door), and refuse anything else (attacking a defeated enemy) with your own codes. - The compiler also emits this C# for Unity (compiled only in Unity):
- The error enum (
unity/<EnumName>.cs). Compare result codes withresult.Is(MyError.NotReady). - The
[RoomInput]enums. Slots are set typed, as inworld.SetInput(MoveInput.X, 1). - The
[RoomAction]enums. Operations are sent by name, as indoor.Interact(DoorAction.Open). - For each sync schema,
unity/<SchemaName>Schema.cs, which contains:- The fields as an enum, and
PrefabandFieldsconstants - Typed reads such as
FighterSchema.Score(o) - Typed writes:
FighterSchema.SetScore(values, 3)into a spawn’s values, andFighterSchema.SetScore(client, id, 3)to an object this client writes. Only the writes the room takes from a client are generated: every field of a player object, writes while holding the lease of a leased object, and only the pose at spawn (position, rotation) of a simulated object a player spawns. Server-managed objects and objects only the rules spawn get none. - Each float field’s step size (
<Field>Precision). The writes do the conversion by the step size and the 1/0 of a bool for you. Changed(mask, field)and the prefab testFighterSchema.Is(o)- For types whose spawn sets the pose, spawn values with the position set:
FighterSchema.Position(x, y)(client.Spawn(FighterSchema.Prefab, FighterSchema.Position(x, y))) - For writable types, writes taking the object:
FighterSchema.SetScore(client, o, 3)
- The fields as an enum, and
- The error enum (
- Typed reads return what the client shows (
NetworkObject.ShownValues):- For an object it predicts, the prediction.
- For an object it writes (its own player object, or an object whose lease it holds), its own latest write. The value reads at once, before it is sent, and an older value arriving late never sets the display back.
- Otherwise, the room’s value.
- Read the room’s latest value with
FighterSchema.Score(o.Values).
- Name constraints:
- The field names
Prefab,Fields,ChangedandShownare taken. - A field whose generated member (
Set<Field>,<Field>Precision) would repeat another member’s name is a compile error. - The generated type names (schema enums and
<SchemaName>Schema,[RoomInput]and[RoomAction]enums, the error enum and<RuleClass>Prediction) must differ, ignoring case.
- The field names
- 2D games may leave out z:
Spawn<T>(x, y),SpawnOwned<T>(owner, x, y),Overlap<T>(shooter, x, y, radius)andRaycast<T>(shooter, x, y, dx, dy, distance). - A float field takes a constant in its units (
Room.Set(id, Door.Angle, 90f), or aconst floatlocal); the compiler converts it with the step size, also in[Predict]methods. A computed value, or a value orDefaultthat is not a whole number of steps, is a compile error.
Room API
From C#, call Room.*; from Lua in GSL, call room.* with the same names. All values are int32.
Define Object Kinds
These can be called only during room initialization (from Start until the first wait for input).
| API | Description |
|---|---|
DefineServerPrefab<TSchema>() | Defines the kind for sync schema TSchema as a server-managed object |
DefineLeasedPrefab<TSchema>(leaseMilliseconds) | Defines the kind for sync schema TSchema as an object whose control is lent to players |
DefineServerPrefab(prefab, fields) | Defines it by directly specifying the Prefab ID and a bitmask of synced fields |
DefineLeasedPrefab(prefab, fields, leaseMilliseconds) | Same as above. Specifies the control lease period in milliseconds |
DefineSimulatedPrefab<TSchema>() / DefineSimulatedPrefab(prefab, fields) | Defines the kind as objects that players spawn and the rules move every tick (ticks) |
DefineRuleSpawnedPrefab<TSchema>() / DefineRuleSpawnedPrefab(prefab, fields) | Like DefineSimulatedPrefab, but players cannot spawn it; only the rules’ SpawnOwned does (projectiles, for example) |
DefineTickRate(ticksPerSecond) | Sets how many times per second Tick runs (1 to 60) |
DefineHitbox<TSchema>(radius) / DefineHitbox(prefab, radius) | Gives objects of the kind a hitbox (a sphere of radius; a circle in 2D). Call after DefineTickRate (lag compensation) |
DefineRelevance<TSchema>(distance) / DefineRelevance(prefab, distance) | Sends updates of objects of the kind less often the farther they are from the receiving player. Call after DefineTickRate (update rate) |
| Management | Who can modify values | Example uses |
|---|---|---|
| Server-managed | Only Room.Set in the rules | Enemy HP, doors, boss phase, score |
| Control lending | Only the one connection that has control. The rules cannot modify them | A carried box, a paddle, an operator seat |
| Simulation | Only Room.Set in the rules. The owning player sends inputs | Player characters, vehicles |
Spawn Objects and Read and Write Values
| API | Description |
|---|---|
Spawn<TSchema>(x, y, z) / Spawn(prefab, x, y, z) | Spawns an object and returns its object ID. x y z are the initial values of the position fields; other fields start at their default (Default) or 0. Spawn<TSchema> works only for a type Start defines with DefineServerPrefab<TSchema>() or DefineLeasedPrefab<TSchema>(ms) (SpawnOwned<TSchema> needs a simulated definition); a missing or different definition is a compile error |
SpawnOwned<TSchema>(ownerObjectId, x, y, z) / SpawnOwned(prefab, ownerObjectId, x, y, z) | Spawns a simulated object owned by the player who owns the ownerObjectId object; it moves by that player’s input (for projectiles and respawns). Returns 0 without spawning when that player already owns 64 objects or the room holds its maximum number of objects (the tick does not fail) |
Despawn(objectId) | Removes a server-managed, leased or simulated object and cancels its timer. Player objects cannot be removed |
Get(objectId, field) | Reads a field value |
Set(objectId, field, value) | Writes a field value. Server-managed and simulated objects only |
Get<TSchema>(objectId, StandardField.PositionX) / Set<TSchema>(objectId, StandardField.RotationY, value) | Reads or writes a standard field (position, rotation) typed. A field that TSchema’s StandardFields do not include is a compile error. A float constant (90f) is converted by the step size |
OwnerOf(objectId) | The connection ID of the owner (player and simulated objects) or of the lease holder (leased objects); 0 when there is none. Use it to tell who operated (== SenderConnectionId()) or who fired a projectile |
Exists(objectId) | Whether the ID names an object. False for IDs of 0 or below and for objects that were removed or left with their player (not an error). Check a stored ID before Get or PrefabOf, which fail for an object that does not exist (and the input’s processing is undone) |
FindOwned<TSchema>(connectionId) / FindOwned(prefab, connectionId) | The first object of the type, by ID, whose owner (or lease holder) is the connection; 0 when there is none. FindOwned<Fighter>(Room.OwnerOf(rocket)) finds the character of the player who fired, FindOwned<Fighter>(Room.SenderConnectionId()) the character of the player who operated |
For field, specify a sync schema enum value (such as EnemyFields.Health) or a standard field such as RoomFields.PositionX. With StandardField, the compiler checks that the schema synchronizes the standard field. Values read and written in the rules are reflected in Get immediately within the processing of the same input.
Position values are integers divided by the step size. With the default step size (0.01), 50 corresponds to 0.5 in Unity.
Handle the Passage of Time
| API | Description |
|---|---|
After(objectId, milliseconds, eventId) | Schedules Timer(state, objectId, eventId) to be called once after milliseconds |
CancelTimer(objectId) | Cancels the object’s scheduled timer |
eventId can be a [RoomTimer] enum value as it is (Room.After(id, 8000, DoorTimer.Close)). The wait is 50 to 86400000 milliseconds and eventId is 1 or more; constants outside these ranges are compile errors.
Each object has one scheduled timer; calling After on the same object replaces it. For processing repeated at a fixed interval, schedule the next After inside Timer. Use it for enemy action intervals, the time until a door closes, the wait before reviving, and so on.
Timers are processed in the room about every 50 milliseconds. They are not synchronized with Unity’s rendering frames and are not guaranteed to run at an exact time. A fired timer is consumed even if the rules reject or fail.
Name Operations and Timers (RoomAction, RoomTimer)
Name the method of Interact with an enum marked [RoomAction] and the eventId of Timer with an enum marked [RoomTimer]. Unity gets the [RoomAction] enums too (unity/<EnumName>.cs), so the client’s numbers cannot drift apart. [RoomTimer] numbers stay in the room, so nothing is emitted for Unity.
[RoomAction]
public enum DoorAction { Open = 1, Close = 2 }
[RoomTimer]
public enum DoorTimer { Close = 1 }
public static Step Interact(State state, int objectId, int method) {
switch ((DoorAction)method) {
case DoorAction.Open:
// ...
Room.After(objectId, 8000, DoorTimer.Close); // Timer after 8 seconds (eventId is (int)DoorTimer.Close)
break;
case DoorAction.Close:
// ...
break;
default:
return Step.Ignore(Error.InvalidOperation);
}
return Step.Stay(state);
}// Unity (with a using for the namespace of the generated DoorAction.cs)
door.Interact(DoorAction.Open); // SharedObject
client.Interact(id, DoorAction.Open); // SyncClient
world.RaiseEvent(DoorAction.Open, RpcTarget.All); // a room event's code[RoomAction]values are distinct integers of 0 or more;[RoomTimer]values are distinct integers of 1 or more (the room’s timer events start at 1; give the first member a value too).- In the rules,
[RoomAction]and[RoomTimer]enums convert to and fromintfreely ((DoorAction)method,(int)DoorTimer.Close). switchstatements branch on int, bool, enum and string values, with constantcases anddefault. Each section ends withbreakorreturn; a section in braces declares locals of its own (case 1: { int bonus = 1; ...; break; }). Abreakin the middle of a section is a compile error.- Predicted code uses them the same way (
(int)DoorAction.Open,(Stance)x,switch ((Stance)x),((Stance)x) switch { ... }, and locals or parameters of typeStance). - A plain enum (without
[RoomAction]and the like) cannot be converted to a number in the rules.
Simulate at a Fixed Rate (Ticks)
Rules that define Tick call DefineTickRate in the initialization (without it, the build fails). When the initialization calls DefineTickRate, the room runs Tick(state, int tick) a fixed number of times per second. Use it when the server computes things such as player character movement from inputs. Clients cannot write positions, which prevents tampering with movement speed or walking through walls.
| API | Description |
|---|---|
Input(objectId, field) | Reads the input the owner of a simulated object sent for the current tick (slots 0 to 31). Passing a non-simulated object is an error |
Input(objectId, field, min, max) | Reads the input clamped to min to max |
Input(objectId, MyInput.Slot) | Reads a slot named by a [RoomInput] enum. A slot with [InputRange(min, max)] reads clamped to its range |
ObjectCount<TSchema>() / ObjectCount(prefab) | The number of objects of the kind (including those spawned in this processing) |
ObjectAt<TSchema>(index) / ObjectAt(prefab, index) | The ID of the kind’s index-th object (in ascending ID order) |
// Position is the standard XYZ (fields 0..2, 0.01 units); custom fields start at 6.
[RoomSchema(5, StandardFields = RoomSync.Position)]
public enum Character { PositionX = 0, PositionY = 1, Hits = 6 }
// Input slots; the room reads them clamped to their range.
[RoomInput]
public enum MoveInput { [InputRange(-1, 1)] X = 0, [InputRange(-1, 1)] Y = 1 }
public static Step Start() {
Room.DefineTickRate(30);
Room.DefineSimulatedPrefab<Character>();
return Step.WaitFor(nameof(Tick), new State(0));
}
public static Step Tick(State state, int tick) {
int count = Room.ObjectCount<Character>();
for (int i = 0; i < count; i++) {
int id = Room.ObjectAt<Character>(i);
// The spawn position comes from the client: limit it before adding to it.
int x = RoomMath.Clamp(Room.Get(id, Character.PositionX), -10000, 10000);
int y = RoomMath.Clamp(Room.Get(id, Character.PositionY), -10000, 10000);
Room.Set(id, Character.PositionX, x + Room.Input(id, MoveInput.X) * 10);
Room.Set(id, Character.PositionY, y + Room.Input(id, MoveInput.Y) * 10);
}
return Step.Stay(state);
}- The parameter of
Tickmust be namedtick(the tick number, starting at 1). A definition that usesDefineTickRatewithoutTickfails to compile. Tickruns only while the current input wait accepts it. You can wait for it together withInteractandTimer(.Or(nameof(Interact))). IncludeTickin every wait the simulation should continue in; elsewhere the tick number still advances.- A tick whose
Tickfails changes nothing, and the next tick runs normally. - Inputs are values players send freely: any
intcan arrive in any slot. The position and rotation a simulated object spawns with are also chosen by the client. Limit their range before using them in calculations (a slot with[InputRange],Room.Input(id, slot, min, max), orRoomMath.Clamp). IfTickfails because of an overflow or similar error, the whole tick is discarded for everyone. Until a new input arrives, the same input keeps being used, so the entire room stops. - A
[RoomInput]enum is also emitted for Unity (unity/<EnumName>.cs). Clients set inputs by the same names, as inworld.SetInput(MoveInput.X, value). - When you
Despawninside a loop, iterate from the end.ObjectAtreflects the removal at once, so a forward loop skips the next object. - Objects of a
DefineSimulatedPrefabkind are spawned by clients like player objects and owned by that player. A client may spawn one object of each such kind, and only the schema’sStandardFields(without them, the position fields 0 to 2) are taken from the request; other fields start at their default or 0 whatever the client sends. Only the rules can write or remove them; the owner’s writes and removals are rejected. Their ownership cannot be transferred. They are deleted when the owner leaves. - A definition that uses
Input,DefineHitbox,DefineRelevance,RaycastorOverlapwithoutDefineTickRatefails to compile. - Players send inputs tagged with the tick they are meant for. When a tick’s input has not arrived, the previous input is used.
- Values changed by ticks reach clients with the periodic updates (over UDP when available).
- When processing falls behind, the room runs at most 3 ticks at once and skips the rest.
- The rules compute with integers only. Positions are integers divided by the step size (0.01 by default).
Hit What the Shooter Saw (Lag Compensation)
Other characters on a player’s screen are slightly in the past, by the network delay and interpolation. Testing hits against their current positions misses shots that hit on screen. The client sends with every input how far behind its screen was, so the room can test hits at the positions the shooting player saw.
public static Step Start() {
Room.DefineTickRate(30);
Room.DefineSimulatedPrefab<Character>();
Room.DefineHitbox<Character>(50); // after DefineTickRate
return Step.WaitFor(nameof(Tick), new State(0));
}
static void Fire(int id) {
if (Room.Input(id, 2) == 0) return;
int target = Room.Raycast<Character>(id,
Room.Get(id, RoomFields.PositionX), Room.Get(id, RoomFields.PositionY), 0,
Room.Input(id, 3), Room.Input(id, 4), 0, 2000);
if (target != 0) Room.Set(target, Character.Hits, Room.Get(target, Character.Hits) + 1);
}| API | Description |
|---|---|
Raycast<TSchema>(shooterId, x, y, z, dx, dy, dz, distance) | The ID of the first object hit by the line from (x, y, z) in the direction (dx, dy, dz) up to distance, or 0 |
Overlap<TSchema>(shooterId, x, y, z, radius) | The ID of the nearest object overlapping the sphere of radius, or 0 |
- A hitbox is a sphere centered on the position fields (0 to 2, the standard Position). In a 2D game, keep Z at 0 to treat it as a circle.
- When
shooterIdis a simulated object, other objects are moved back to where its owner saw them when sending the current tick’s input, interpolating between ticks, by at most 500 milliseconds.shooterIditself is never hit. shooterIdmust be an existing object (0 is not allowed).- The origin and direction are used as given. Pass the shooter’s current position (its owner’s client predicts it, so it matches the screen).
- These cannot be called from
[Predict]code. On the client, show only effects immediately and apply damage after the room’s result arrives.
Send Distant Objects Less Often
In a room with many players, sending everyone’s position to everyone every tick takes a lot of bandwidth. With DefineRelevance, updates of objects of that kind reach each player less often the farther they are from that player’s character.
Room.DefineRelevance<Character>(300); // after DefineTickRate| Distance from the receiving player’s character | Update rate |
|---|---|
Within distance | Every tick |
| Within twice it | Every 2 ticks |
| Within four times it | Every 4 ticks |
| Farther | Every 8 ticks |
- The distance is measured on the position fields (0 to 2) from the nearest simulated object the player owns. Your own character arrives every tick.
- Values changed in between arrive with their latest values the next time the object is sent. Display is interpolated, so distant characters still move smoothly.
- Players owning no simulated object (spectators, for example) receive every tick.
- The resend every second and values sent right before RPCs and similar commands are not thinned out.
- For example, with 64 players spread over 20 m square and all moving (
distance300), update traffic drops to about a third.
Move Objects on the Client First (Prediction)
Put the code that moves one object in a private helper and mark it with [Predict(typeof(Schema))]. The owner’s client then runs it too, so your own character moves the moment you press the input.
public static Step Tick(State state, int tick) {
int count = Room.ObjectCount<Character>();
for (int i = 0; i < count; i++)
Move(Room.ObjectAt<Character>(i), tick);
return Step.Stay(state);
}
[Predict(typeof(Character))]
static void Move(int id, int tick) {
int x = RoomMath.Clamp(Room.Get(id, Character.PositionX), -10000, 10000);
Room.Set(id, Character.PositionX, x + Room.Input(id, MoveInput.X) * 10);
}TSchemaof[Predict(typeof(TSchema))]is defined inStartwithDefineSimulatedPrefab<TSchema>()orDefineRuleSpawnedPrefab<TSchema>(); a missing or different definition is a compile error (clients predict only the simulated objects they own).- The helper must be
private static void Name(int objectId)or(int objectId, int tick), one[Predict]per schema. In the room,Tickcalls it as usual. - Each tick, the client runs the
[Predict]helpers in the orderTickfirst calls them, one helper over all objects of its kind before the next (like Arena’sAct, thenFly). A[Predict]helper thatTicknever calls is a compile error. - The compiler also emits this helper and the helpers it calls as C# for Unity (
unity/<RuleClass>Prediction.cs). Values are computed with the same integer arithmetic as the room. - Predicted code can use int and bool values,
System.Math.MinandMax,RoomMath, helpers of the rule class, andRoom.Get,GetBool,Set(includingStandardField),Input,ObjectCount,ObjectAt,SpawnOwned,Despawn,Is,PrefabOf,OwnerOf,ExistsandFindOwned(and[RoomAction]values). All computation uses int or bool (schema fields by name; casts to a schema enum are not allowed). Anything else (float, static fields, reading thestateand so on) is a compile error. - Calling
SpawnOwnedin predicted code (launching a projectile, for example) shows the projectile on the shooter’s screen at once (predicted spawn). When the projectile spawned by the room arrives, it takes over the same object on screen; if the room did not spawn it, it disappears. To match projectiles correctly, callSpawnOwnedonly in predicted code and keep hit tests in code that only the room runs. Spawning a kind withSpawnOwnedin predicted code and also in other code (a respawn, for example) is a compile error. In predicted code, name the kind withSpawnOwned<TSchema>or a constant. - On the client, other players’ inputs read as 0 and other objects have the latest values received from the room. Predictions can miss, for example when characters collide, and are corrected by the room’s results.
Integer Math (RoomMath)
Integer functions for the rules and predicted code. The room and Unity’s predictions compute the same results. A result outside int32 is an error, like ordinary arithmetic overflow.
| API | Description |
|---|---|
RoomMath.Clamp(value, min, max) | Clamps to min to max (min > max is an error) |
RoomMath.Abs(value) / Sign(value) | Absolute value / sign (-1, 0 or 1) |
RoomMath.Sqrt(value) | Integer square root (rounded down; a negative value is an error) |
RoomMath.Length(x, y) / Length(x, y, z) | Length of a vector (rounded down; computed in double precision) |
RoomMath.MulDiv(value, numerator, denominator) | value * numerator / denominator without an intermediate overflow, truncated toward zero. Scaling a direction to a speed: MulDiv(dx, speed, RoomMath.Length(dx, dy)) |
Random numbers (Room.Random)
Room.Random(min, max) returns an integer from min to max inclusive, every value equally likely. min > max is an error. It works in every handler, including Start.
public static Step Interact(State state, int objectId, int method) {
var damage = 100;
if (Room.Random(1, 100) <= 25) damage *= 2; // a critical hit 25% of the time
Room.Set(objectId, Boss.Health, Room.Get(objectId, Boss.Health) - damage);
return Step.Stay(state);
}- Only the room draws. Its seed is made when the room starts and is never sent to clients.
- Draws are committed together with the processing of one input. When
Step.Ignoreor an exception rolls the processing back, the next processing that commits draws the same values, so players cannot reroll by making an input fail. - Predicted methods (methods marked
[Predict]and the methods they call) cannot use it (a compile error), because clients cannot draw the same values. Write the outcome to a field or send it with an RPC, and show it when it arrives. - Players who join late or reconnect receive the field values, so nothing more about random numbers needs to be sent.
Records of records and arrays
Room rules’ records may hold other records and arrays (of int, bool, string, enums or records), in the state and in participant data.
public record State(int Boss, Member[] Party, int[] Log);
public record Member(int Hp, Gear Gear);
public record Gear(int Power);
// Lower the first member's Hp and log the damage dealt
var party = RoomList.With(state.Party, 0, state.Party[0] with { Hp = state.Party[0].Hp - 10 });
return Step.Stay(state with { Party = party, Log = RoomList.Append(state.Log, damage) });- A record that contains itself is a compile error (through an array it is allowed). Arrays of arrays are not supported.
- Arrays are values like records: never
nulland never changed in place (a[i] = xand==between arrays are compile errors). - Read them with
a.Lengthanda[i](an index outside the array makes the processing fail). Make them withnew[] { ... }, ornew int[n]/new bool[n]filled with 0 / false. - To change one, take a changed copy from
RoomList.With(a, i, value)(replace an element),RoomList.Append(a, value)(add at the end) orRoomList.RemoveAt(a, i)(remove). - Update nested values as
state with { Hero = state.Hero with { Hp = 0 } }. - Predicted methods compute ints and bools only, so they do not use records or arrays.
Participant data (Room.Participant)
Data GS2 holds about each participant, such as a character’s rank, grade or equipment, is read with Room.Participant<T>(connectionId). Unlike values a client sends, players cannot change it.
public enum Element { Fire, Water }
public record Hero(int Attack, int Rank, Element Element);
public static Step Interact(State state, int objectId, int method) {
var hero = Room.Participant<Hero>(Room.SenderConnectionId());
var damage = hero.Attack + hero.Rank * 10;
if (hero.Element == Element.Water) damage += 20;
Room.Set(objectId, Boss.Health, Room.Get(objectId, Boss.Health) - damage);
return Step.Stay(state);
}-- The participant script (GS2-Script)
result = { participant = { Attack = 120, Rank = 3, Element = "Fire" } }- Set the namespace’s
participantSettingto the GS2-Script that makes the data and the GS2-Identifier user it runs as. Grant the user only what it needs, such as running the script. - When a player joins, the room runs the script with
args.userIdand completes the join once it hasresult.participant(notifications to the other participants andSpawnedcome after). If the script fails, the join is refused. - The data of a user’s first join is used while the room lasts; reconnecting does not fetch it again.
Tis a record of the rules whose fields are int, bool, string, enum (a member’s name as a string), and records and arrays of them. A field the script does not return, or returns with another type, makes the processing fail; keys that are not fields of the record are ignored.- A connection without data (no
participantSetting, not a participant) is an error. - Predicted methods cannot use it (a compile error). Copy what the prediction needs (such as a movement speed) into a field in
Spawned.
Respond to Spawns (Spawned)
When a player spawns their own object (a player object or a simulated object), Spawned(state, int objectId) is called if the rules are waiting for it. Use it to place objects at each team’s spawn point or to set initial values.
public static Step Spawned(State state, int objectId) {
int team = Room.SenderConnectionId() % 2;
Room.Set(objectId, Character.PositionX, team == 0 ? -500 : 500);
return Step.Stay(state);
}- Like
TickandInteract, include it in what you wait for (.Or(nameof(Spawned))). It is not called while the rules are not waiting for it. - The parameter name is fixed to
objectId.Room.SenderConnectionId()is the player who spawned the object. - The spawn other players receive already carries this handler’s changes. An object it removes reaches nobody. If it fails, its changes are discarded and the object stays as spawned.
- Returning
Step.Ignore(code)or removing the object refuses the spawn (player objects too): it reaches nobody, and the player’s spawn request is refused withcode(Forbiddenwhen removed). Objects created in this handler arrive after the spawn that created them. - It is called for every object a player spawns. Tell the kinds apart with
Room.Is<TSchema>(objectId)orRoom.PrefabOf(objectId).
Find the User Who Operated
| API | Description |
|---|---|
SenderUserId() | The userId of the player who operated. Taken from the access token; clients cannot rewrite it |
SenderConnectionId() | The ID of the connection that operated. Changes on reconnection. Connection IDs are always positive (1 to 2147483646), so % 2 is 0 or 1, and they compare with OwnerOf |
Start and Timer have no operating player, so SenderUserId() returns an empty string and SenderConnectionId() returns 0. If timer processing needs to know “who started the operation”, save it in the state record while processing Interact.
When managing per-player ownership or turn order, use SenderUserId(), which does not change on reconnection.
Sync Schema
Declare the synced values of shared objects with an enum that has the RoomSchema attribute. Both the rules definition and the Unity sync schema (.realtimeschema) are generated from this declaration.
[RoomSchema(7, StandardFields = RoomSync.Position)]
public enum EnemyFields
{
Health = 6,
}
[RoomSchema(8)]
public enum SwitchFields
{
[RoomField(typeof(bool))] IsOpen = 6,
[RoomField(typeof(float), Precision = 0.01f)] Progress = 7,
}| Item | Description |
|---|---|
RoomSchema(prefab) | Prefab ID. A positive int32 that must not duplicate other sync schemas |
StandardFields | Standard fields for position and rotation. RoomSync.Position (fields 0 to 2), RoomSync.Rotation (3 to 5), RoomSync.Transform (both) |
PositionPrecision / RotationPrecision | Step size of the standard fields. Defaults are 0.01 and 360 / 4096 degrees |
| Enum values | Field numbers on the wire (0 to 31). Use 6 or higher so they don’t overlap with the standard field numbers |
RoomField(typeof(...)) | Type in Unity. int (default), bool, float |
Precision | Step size of a float. The rules handle it as an integer, and Unity receives it as “integer × step size” |
Default | The initial value of objects of a kind the rules define (Define*Prefab<T>()), a value of the field’s type (Default = 100, Default = true, Default = 1.25f). Applies to objects the rules spawn and to players’ characters, except fields the spawn sets (the position, a player’s pose). Unity’s predicted spawns start with the same value |
In the example above, if you Set 125 to Progress, Unity receives 1.25f. A bool field reads and writes as a bool with Room.GetBool(id, SwitchFields.IsOpen) and Room.Set(id, SwitchFields.IsOpen, true) (stored as 1 and 0).
In a schema with StandardFields, the enum may name the standard fields by their standard name and number (PositionX = 0) to read and write them typed, as in Room.Get(id, Character.PositionX); coordinates outside StandardFields cannot be written that way. Standard fields take no RoomField. A custom field on a standard field’s number is an error that names the numbers to use.
The files generated for Unity (sync schemas and predictions) record the rules they come from (a hash of the GSL). When the room runs other rules, Unity’s NetworkWorld logs a warning. After changing the rules, copy the regenerated files.
Field numbers are identifiers on the wire. After release, do not change them or let them shift by reordering.
Processing and Rollback per Input
Changes made by a single input (Interact or Timer) are committed together or rolled back together.
| Rules result | Behavior |
|---|---|
Step.Next | Proceeds to the next processing as part of the same input |
Reaching a wait for input (WaitFor / Stay), Step.End | Commits changes to the state, shared objects, and timers, and delivers them to everyone |
Step.Ignore | Rolls back all changes made by this input (including random draws). The reason reaches the client |
| Exception, exceeding the execution time or transition count limit | Rolls back all changes made by this input. The client receives InvalidOperation |
The reason value of Step.Ignore reaches the operating client’s CommandCompleted as is. Values below 100 share the range of the room’s result codes (MissingObject, etc.), so use values of 100 or more for your rules’ own reasons (error enum). For the list of results the client receives, see How Object Sync Works.
Step.End only ends execution of the rules; it does not destroy shared objects or end the room.
Generation and Registration
| Step | Description |
|---|---|
| Generate | Generate with RealtimeRoomV1 specified for hostProfile in project.json. For the settings, see C# definition generation settings |
| Register | Specify the contents of the generated main.gsl as payload of GS2-StateMachine’s UpdateStateMachineMaster. mainStateMachineName is the class name of the rules |
| Configure the room | In the Realtime namespace, specify the server type stateMachine and the namespace where the rules are stored (stateMachineSetting.namespaceId). If you omit the version (stateMachineSetting.version), the latest is used; specify it only when you want to pin one |
The generated files are as follows.
| File | Purpose |
|---|---|
main.gsl | The rules to register |
package.zip | A distribution file containing only main.gsl. When registering, read out the main.gsl inside and specify it as payload |
unity/<schema name>.realtimeschema | The sync schema to specify on Unity’s NetworkEntity |
source-map.json | A development file for tracing generated locations back to the original C#. Not used for registration |
A room loads the rules once when it is allocated. If the version is omitted, it loads the latest rules at that time; if specified, it loads that version. If no rules are registered in the storage namespace, or if loading or initialization fails, the room is not used. A running room uses the same version until it ends, and new rules are used by rooms allocated afterwards.
Distribute the rules (GSL) and the sync schema as a pair generated together from the same C# definition.
Limits
| Target | Limit |
|---|---|
| Participants per room | 64 connections |
| Shared objects per room | 4096 |
| Object kinds | Up to 64 defined during initialization. Up to 4096 for the whole room |
| Fields per object | 32 (numbers 0 to 31) |
| Control lease period | 50 milliseconds to 1 day (86,400,000 milliseconds) |
After wait time | 50 milliseconds to 1 day (86,400,000 milliseconds) |
After eventId | 1 or more |
| Scheduled timers | One per object, 4096 for the whole room |
| Changes per input | Up to 64 objects each for spawns and value changes. Up to 64 objects for scheduling and canceling timers |
| Processing per input | 100 milliseconds of execution time, up to 32 transitions via Next |
| Timers executed per processing cycle | Up to 64. Any excess is carried over to the next cycle |
| Tick rate | 1 to 60 per second |
| Changes per tick | Value changes, spawns and despawns: up to 1024 objects each. One player owns up to 64 objects |
| Hit test rewind | Up to 500 milliseconds (positions are kept for 1 second) |
| Inputs sent ahead | Up to 1 second of ticks |
| Size of the rules (GSL) | 1 MiB |
Unsupported Features
Room rules run only processing that is self-contained within the room. The following features are not available.
GameRewards(granting rewards),GameRandom(useRoom.Randomfor random numbers)- GSL
Script(calling GS2-Script) - Access to external APIs, files, or the network (read each participant’s GS2 data with
Room.Participant) - Unity APIs or arbitrary .NET libraries
For the C# syntax you can use in rules, see the C# Definition Reference.
Writing GSL Directly
You can also write GSL directly without C#. For the basic GSL syntax, see GSL Format. GSL that runs in a room follows these rules.
The state variables are
map runandmap execution.Events received by a
WaitTaskthat waits for input use the following signatures.Event Parameters Interactint revision, int objectId, int methodTimerint revision, int objectId, int eventIdTickint revision, int tickCall Room APIs such as
room.Spawnfrom the Lua written in a Task’s Payload. Draw random numbers withroom.Random(min, max); Lua’smath.randomis not available.Calling GS2-Script via
Scriptis not available.