Manual
Manual
C# in a game
A game's own code is C#: the components it declares, the systems that run on them, and the plugins that add those systems. This page shows how each is written, along with resources, settings and data assets declared in code, code that waits across frames, typed keys for assets, and what happens when you change code with the editor open.
A game's C# project
A game is a folder with a C# project in it. The Hub's New Project makes one from a template:
MyGame/
MyGame.csproj the game's C# project
assets/ scenes, models, textures, prefabs
scripts/ the game's C#
settings/ the project's settings, a JSON file eachThe project names the engine as an MSBuild SDK, and needs nothing else:
<Project Sdk="AbyssEngine.Sdk/0.4.0" />The SDK builds the game with .NET 10, with unsafe code and nullable references on, and adds the engine's source generators, which write the code that connects your types to the engine. The entry point in scripts/Program.cs is one line, the same for every game:
[STAThread]public static int Main(string[] args) => AbyssGame.Run(args);AbyssGame is generated: it registers every component your game and its packages declare, then hands over to the engine, which opens the window and the first scene of the build. Every type of yours must be in the game's namespace or one inside it, which by default is the project's name; a type outside it is a build error (ABYSS027).
The editor builds this project when it opens the game. You can also run it from its folders with dotnet run. Your first project walks through making one.
Declaring a component
A component is a partial struct marked [AbyssComponent]. The Project panel's Component Script makes one for you in scripts:
using System.Runtime.InteropServices;using Abyss.Core;
namespace MyGame;
[AbyssComponent][StructLayout(LayoutKind.Sequential)]public partial struct Swing{ [Range(1f, 20f)] [Tooltip("How long it stays open, or shut, in seconds.")] public float Every = 4f;
[HideInInspector] public float Since;
public int Slams;}The generator measures where each field is and tells the engine, so the Inspector can show the fields and a scene can save them. A field's initializer is where it starts: Add Component, a spawn and a scene that leaves the field out all give it that value.
[AbyssComponent] takes two settings. Name is the name the engine knows the component by, the type's full name if you leave it out. Page is the page that documents it, which the ? on its header in the Inspector opens, and F1 with the pointer over it. It is a whole address, [AbyssComponent(Page = "https://example.com/docs/swing")], or a path in this manual. Without one, your component's header has no ?.
A field can hold:
- a number (
byte,sbyte,short,ushort,int,uint,long,ulong,float,double) or abool; - a
Vector2,Vector3orVector4, or a struct whose own fields are of these kinds; - an enum, shown as a list of its names, or a
[Flags]enum, shown as ticks; - a list held inside the component,
FixedList8<T>up toFixedList128<T>, and text,FixedText32up toFixedText256; a list that grows as it needs is a component of its own, see Lists; - a text of any length,
SharedText, see Texts; - a string of the game's,
LocalizedString, said in the player's language, see Strings in components; - a reference:
PrefabReffor a prefab,AssetRef<T>for a data asset,EntityReffor another entity, andFileReffor a file; - a
LayerMask, shown as the layers to tick.
A field of a type the engine cannot describe, such as a char or a decimal, is still stored, and the build warns that the Inspector will not show it (ABYSS013).
These attributes shape how the Inspector shows a field:
| Attribute | What it does |
|---|---|
[Range(min, max)] | A slider for a number; what is dragged or typed stays inside the range. Systems may still write any value. |
[Tooltip("...")] | The text shown when the pointer rests on the field's name. |
[HideInInspector] | Leaves the field out of the normal view. It is still saved and still shown in the Debug view. |
[ColorUsage] | Shows a Vector3 or Vector4 as a color swatch that opens the color picker. [ColorUsage(false)] hides alpha, and [ColorUsage(true, true)] allows HDR values past 1. |
[FileKind(".abynav")] | Makes a FileRef slot accept only files with that extension. |
[FormerlySerializedAs("Old")] | Keeps a field's saved value when you rename it. On the struct, it does the same for a renamed component. |
[SerializeAllFields] | On the struct: scenes write every field, even those at their default, so changing a default later does not change saved scenes. |
Writing a system
Mark a static method [AbyssSystem] in a partial type. The generator reads the parameters as the system's query and writes an Add method for it:
public static partial class Wobbling{ [AbyssSystem(Parallel = true)] [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void Bob(ref Transform transform, ref Wobble wobble, in SystemContext context) { wobble.Phase = (wobble.Phase + (wobble.Speed * context.DeltaTime)) % MathF.Tau; transform.TranslationY = wobble.Height * MathF.Sin(wobble.Phase); }}
// In a plugin's Build:Wobbling.AddBob(schedule, world.Transform(), world.Component<Wobble>());| Parameter | Meaning |
|---|---|
ref T / in T | Write or read component T, one entity at a time |
Span<T> / ReadOnlySpan<T> | Write or read component T, a whole chunk at a time; you write the loop |
DynamicList<T> / ReadOnlyDynamicList<T> | Write or read list T, one entity at a time; ListColumn<T> / ReadOnlyListColumn<T> a chunk's |
ChildrenView | Read the entities under each entity, its children; ChildrenColumn a chunk's. Passed world.Children() |
NameView | Read each entity's name; NameColumn a chunk's. Passed world.Name() |
Res<T> / ResMut<T> | Read or write resource T |
in SystemContext | The frame's DeltaTime, plus commands, assets, scenes, input and gizmos |
Keep [MethodImpl(MethodImplOptions.AggressiveInlining)] on a per-entity system. Without it, the call for each entity is not inlined and the system runs several times slower, so the build warns (ABYSS010). Fixed = true runs the system at the fixed rate, and Parallel = true spreads it across cores; Entities, components and systems explains both.
The generated forms do not hand you entity ids. A system that needs them, to despawn an entity or check whether the editor has it selected, is written by hand with schedule.Add: its terms, then a body that loops over the chunks.
schedule.Add("Doors", [swing.Write()], default, [clips.Write()], context =>{ ref DoorClips loaded = ref context.ResourceMut<DoorClips>(0).Value; foreach (Chunk chunk in context.Chunks) { Span<Swing> doors = chunk.GetSpan<Swing>(0); ReadOnlySpan<ulong> entities = chunk.Entities; // ... }}, structural: StructuralAccess.None.AndAnimate);Columns are numbered in the order of the terms, and resources in the order of the resource terms. Log.Info, Log.Warning and Log.Error write to the editor's Logs panel.
Plugins
A plugin adds systems to the game. It implements IPlugin, and the assembly names it once:
using Abyss.Core;using MyGame;
[assembly: AbyssPlugin<MyGamePlugin>]
namespace MyGame;
public sealed class MyGamePlugin : IPlugin{ public void Build(Schedule schedule) { World world = schedule.World; Wobbling.AddBob(schedule, world.Transform(), world.Component<Wobble>()); }}Build runs each time the game starts playing: when the built game starts, and at every Play in the editor. Anything the plugin keeps in its fields starts fresh each time. Reach your components with world.Component<T>(): they are registered before any plugin is built, and registering one again would declare a second component that nothing carries.
A package's plugins are built before the game's own. Plugins named in one assembly are built in no particular order, so a plugin that depends on another builds it itself with schedule.AddPlugin.
Two attributes change when a plugin runs:
[ExecuteAlways]: its systems also run while the game is being edited, so something placed from numbers in the Inspector moves as you type them. What they change while editing is saved with the scene. A system that should act only in play checksworld.GameMode.[EditorOnly]: the editor builds and runs it, and a built game never does. This is where you put help for whoever edits the game. Its systems draw lines over the Scene panel withcontext.Gizmos, and read what is selected fromcontext.Selection. ItsBuildcan also give a component handles in the Scene panel (schedule.EditInScene), add a note under a component in the Inspector (schedule.NoteInEditor), add menu items (schedule.ToolsMenu,schedule.EntityMenu,schedule.ComponentMenu) and open a window of its own (schedule.EditorWindow).
Resources
A resource is an unmanaged struct that the world holds once. Register it and give it a value in Build:
ResourceType<Score> score = world.RegisterResource<Score>();world.InsertResource(score);world.ResourceValue(score) = new Score { Lives = 3 };
Scoring.AddCount(schedule, score); // a system taking ResMut<Score>Registering the same type again returns the same resource, so a plugin built at every Play keeps one. Stop in the editor puts a game's resources back to what they were at Play.
Project settings declared in code
A struct marked [ProjectSettings] becomes a page of Edit ▸ Project Settings, a file under settings, and a resource every world has from the start:
[ProjectSettings("Difficulty")]public partial struct DifficultySettings{ [Range(0, 100)] [Tooltip("How much a hit from an enemy takes away.")] public int EnemyDamage = 10;
public float SpawnEvery = 2f;}The page is drawn with the Inspector's rows and saved to settings/difficulty.json, which a built game carries. A system reads the settings as Res<DifficultySettings> (reach the resource with world.Resource<DifficultySettings>()), and other code with world.Settings<DifficultySettings>(). A game may change its settings while it plays, but only for that run: the file belongs to the project, and Stop puts the values back.
Data assets declared in code
A struct marked [DataAsset] is a kind of asset file you create from the Project panel and edit in the Inspector:
[DataAsset("Weapon", Menu = "Combat")]public partial struct Weapon{ [Range(0, 100)] public int Damage = 10; public float Cooldown = 0.5f;}
[AbyssComponent]public partial struct Wielder{ public AssetRef<Weapon> Held; // a slot that accepts only Weapon assets}Create ▸ Combat ▸ Weapon makes a .asset file. A system reads it with context.Assets.Data(wielder.Held), which loads it the first time and keeps it.
Code that is not a system
A system cannot wait: it runs once a frame and returns. A game also does things that take time, such as a wave of enemies one after another, a download, or signing in. Those go in places of their own, which all run on the engine thread between frames, where the code can change the world freely.
A flow is an async method the schedule starts once the game has started:
schedule.AddFlow("Moons", static async flow =>{ while (true) { await flow.Seconds(4f); // the game's time: none passes while it is paused SceneId moons = flow.Scenes.Load(Addresses.Scenes.Moons, SceneMode.Additive); await flow.Loaded(moons);
await flow.Seconds(4f); flow.Scenes.Unload(moons); await flow.Unloaded(moons); }});A flow waits with NextFrame, Seconds, Until, and Loaded or Unloaded. The code after an await runs on the engine thread before the next frame's systems, even when what it awaited, such as a web request, ran elsewhere.
A plugin can also implement three hooks. BeforeFirstScene(GameStart start) runs before the first scene opens, and may await and choose that scene. Started(World world) runs once the first scene is open. Stopping(World world) runs as the game stops, to save or sign out.
Services hold objects a game keeps that are not ECS data, such as an HttpClient or a connection, one of each type:
schedule.World.Services.Add(new HttpClient());HttpClient http = context.Services.Get<HttpClient>(); // from a system, a flow or a hookEverything stops with the game. Stop in the editor, quitting, or rebuilding the scripts cancels the Stopping token, no awaited code resumes afterward, and the editor disposes the services the game added.
Typed keys for assets
When an asset is marked Addressable, the build writes a typed key for it, and you load it by that key:
PrefabId enemy = context.Assets.LoadPrefab(Addresses.Enemy);ClipId run = context.Assets.LoadClip(Addresses.Characters.Fox.Run); // a clip of characters/fox.glbSceneId level = context.Scenes.Load(Addresses.Levels.First);IReadOnlyList<PrefabId> wave = context.Assets.LoadPrefabs(Labels.Wave1);Addresses has a class for each folder of an address, and the keys of a model's clips, meshes and materials sit under the model's key. A key has the asset's kind, so passing a clip where a prefab is expected does not compile, and a key for an asset whose address changed, or that is no longer Addressable, stops the build at the line that uses it. Loading by a string is a build error (ABYSS026). To keep a reference in a save file, store the key's identity, Addresses.Swords.Long.Id, and rebuild the key from it with PrefabAddress.FromId. Assets, identities and addresses explains addresses and labels.
Changing code while the editor is open
Save a change to your C# and switch back to the editor, or press Ctrl+R (File ▸ Refresh). The editor builds the scripts and loads them again with the scene as it was, and each component keeps its values by field name. Rename a field with [FormerlySerializedAs] to keep its value across the rename, in the editor and in every saved scene and prefab.
Every Play also loads the game's C# afresh, as a built game starts: a static field holds what its initializer says, not what the last Play left in it. The plugins marked [ExecuteAlways] and [EditorOnly] are built again from that fresh load too.
A game's Rust works differently: it is loaded only when the editor starts. Rust in a game covers it.
In the Scripting API
- AbyssComponentAttribute and AbyssSystemAttribute: a component and a system declared.
- IPlugin, ExecuteAlwaysAttribute and EditorOnlyAttribute: what adds systems, and when they run.
- ProjectSettingsAttribute and DataAssetAttribute: settings and data assets declared.
- Flow: code that waits across frames.
- PrefabRef and EntityRef: fields that name a prefab and an entity.
