Class GameExtensions
Provides extension methods for the Game class to simplify common game setup tasks, such as adding cameras, lights, and ground entities, as well as configuring scenes and running the game with custom logic.
public static class GameExtensions
- Inheritance
-
GameExtensions
Remarks
These need nothing from the scene, which is why they take IGame rather than
Game. They sit in this partial file, apart from the scene-building
helpers, because in the engine they belong to the Stride.Games layer below Stride.Engine;
keeping that seam in the file layout, but not in the namespace, means a caller needs one
using for everything on game. while an upstream move would still be a file move.
Methods
Add2DCamera(Game, string?, Vector3?, Vector3?)
Adds a 2D camera entity to the game's root scene with customizable position and rotation, defaulting to orthographic projection.
public static Entity Add2DCamera(this Game game, string? cameraName = "Main", Vector3? initialPosition = null, Vector3? initialRotation = null)
Parameters
gameGameThe Game instance to which the camera entity will be added.
cameraNamestringName for the camera entity and camera slot. Defaults to "Main". If null, the entity is not named.
initialPositionVector3?Initial position for the camera entity. If not provided, the camera will be positioned at a default 2D position.
initialRotationVector3?Initial rotation for the camera entity specified in degrees. If not provided, the camera will be rotated to the default 2D orientation.
Returns
- Entity
The created Entity object representing the 2D camera.
Remarks
The camera entity will be created with an orthographic projection mode and added to the game's root scene. It will also be assigned to the first available camera slot in the GraphicsCompositor.
Add2DCameraController(Game, string?, Keys, bool)
Adds a 2D camera controller to the specified camera entity in the game's current scene.
public static Entity Add2DCameraController(this Game game, string? cameraName = "Main", Keys helpToggleKey = Keys.F2, bool helpCollapsed = true)
Parameters
gameGameThe game instance containing the scene and camera entities to which the controller will be added.
cameraNamestringThe name of the camera entity to attach the 2D camera controller to. If not specified, the main camera name is used.
helpToggleKeyKeysThe key that collapses and expands the camera's help.
helpCollapsedboolWhether the help starts collapsed to a single reminder line. Collapsed by default.
Returns
- Entity
The camera entity to which the 2D camera controller was added.
Remarks
This method extends the game to simplify attaching a 2D camera controller to a camera entity. The camera entity must exist in the root scene; otherwise, an exception is thrown.
Exceptions
- InvalidOperationException
Thrown if no camera entity with the specified name exists in the current scene.
Add2DGraphicsCompositor(Game, Color?, MultisampleCount)
Adds a 2D graphics compositor to the specified game, optionally setting a clear color.
public static GraphicsCompositor Add2DGraphicsCompositor(this Game game, Color? clearColor = null, MultisampleCount msaa = MultisampleCount.None)
Parameters
gameGameThe game to which the 2D graphics compositor will be added. Cannot be null.
clearColorColor?The color used to clear the screen. Defaults to CornflowerBlue if not specified.
msaaMultisampleCountMultisample anti-aliasing level. Defaults to None; use X4 when the scene draws thin geometry such as line meshes, which otherwise flickers as it moves. Clamped to what the device supports.
Returns
- GraphicsCompositor
The newly created 2D graphics compositor.
Remarks
This method sets the graphics compositor of the game's scene system to a default 2D configuration without post-processing effects. The clear color can be specified to customize the background color of the rendered scene.
Add3DCamera(Game, string?, Vector3?, Vector3?, CameraProjectionMode)
Adds a 3D camera entity to the game's root scene with customizable position, rotation, projection mode and default camera name "Main".
public static Entity Add3DCamera(this Game game, string? cameraName = "Main", Vector3? initialPosition = null, Vector3? initialRotation = null, CameraProjectionMode projectionMode = CameraProjectionMode.Perspective)
Parameters
gameGameThe Game instance to which the camera entity will be added.
cameraNamestringName for the camera entity and camera slot. Defaults to "Main". If null, the entity is not named.
initialPositionVector3?Initial position for the camera entity. If not provided, the camera will be positioned at a default 3D position (6, 6, 6).
initialRotationVector3?Initial rotation for the camera entity specified in degrees. If not provided, the camera will be rotated to face towards the origin with default angles (Yaw: 45, Pitch: -30, Roll: 0).
projectionModeCameraProjectionModeThe projection mode for the camera (Perspective or Orthographic). Defaults to Perspective.
Returns
- Entity
The created Entity object representing the 3D camera.
Remarks
The camera entity will be created with the specified projection mode and added to the game's root scene. It will also be assigned to the first available camera slot in the GraphicsCompositor.
Exceptions
- InvalidOperationException
Thrown if the GraphicsCompositor does not have any camera slots defined.
Add3DCameraController(Game, DisplayPosition?, string?, Keys, bool)
Adds a 3D camera controller to the specified camera entity in the game's current scene.
public static Entity Add3DCameraController(this Game game, DisplayPosition? displayPosition = null, string? cameraName = "Main", Keys helpToggleKey = Keys.F2, bool helpCollapsed = true)
Parameters
gameGameThe game instance containing the scene and camera entities to which the controller will be added.
displayPositionDisplayPosition?Where the shared DebugOverlay is drawn. null, the default, leaves the overlay's own position alone; None registers no camera help at all.
cameraNamestringThe name of the camera entity to attach the 3D camera controller to. If not specified, the main camera name is used.
helpToggleKeyKeysThe key that collapses and expands the camera's help.
helpCollapsedboolWhether the help starts collapsed to a single reminder line. Collapsed by default.
Returns
- Entity
The camera entity to which the 3D camera controller was added.
Exceptions
- InvalidOperationException
Thrown if no camera entity with the specified name exists in the current scene.
AddAllDirectionLighting(Game, float, bool)
Adds directional lighting from multiple angles to the current scene, enhancing scene illumination.
public static void AddAllDirectionLighting(this Game game, float intensity = 5, bool showLightGizmo = true)
Parameters
gameGameThe game instance to which the lighting will be added.
intensityfloatThe intensity of the light sources.
showLightGizmoboolWhether to show a gizmo for each light. Default is true.
Remarks
Creates six directional lights, one shining along each world axis, for even lighting from all directions.
AddDirectionalLight(Game, string?, bool, float)
Adds a directional light entity to the game's root scene with optional customization.
public static Entity AddDirectionalLight(this Game game, string? entityName = "Directional Light", bool enableShadows = true, float intensity = 20)
Parameters
gameGameThe Game instance to which the directional light will be added.
entityNamestringOptional name for the new directional light entity. If null, the entity will not be named.
enableShadowsboolWhether the light casts shadows. Defaults to true.
intensityfloatBrightness of the light. Defaults to 20.
Returns
- Entity
The created Entity object representing the directional light.
Remarks
This method creates a directional light with the following default settings: - Intensity: 20.0f - Position: (0, 2.0f, 0) - Rotation: X-axis rotated by -30 degrees and Y-axis rotated by -180 degrees. - Shadow Enabled: True - Shadow Size: Large - Shadow Filter: PCF (Percentage Closer Filtering) with a filter size of 5x5
The entity will be added to the game's root scene. You can customize the light properties by accessing the returned Entity object.
Note that enableShadows only controls shadows cast by geometry onto
other geometry. It does not flatten shading: a surface facing away from the light is still
darkened by the diffuse N·L term, whatever this is set to. For a surface that reads as the same
colour from every angle, use an emissive material such as CreateFlatMaterial(IGame, Color?).
AddEntityTextRenderer(Game)
Registers the renderer that draws EntityTextComponent, once, however many times this is called.
public static void AddEntityTextRenderer(this Game game)
Parameters
gameGameThe game whose compositor the renderer is added to.
Remarks
The screen-space counterpart of AddWorldTextRenderer(Game), with the same failure mode when forgotten: components collect, nothing draws them, and no error says why.
Exceptions
- InvalidOperationException
Thrown if the GraphicsCompositor is not set in the game's SceneSystem.
AddGraphicsCompositor(Game, Color?, MultisampleCount)
Adds a default graphics compositor with post-processing effects enabled to the specified game.
public static GraphicsCompositor AddGraphicsCompositor(this Game game, Color? clearColor = null, MultisampleCount msaa = MultisampleCount.None)
Parameters
gameGameThe game to which the graphics compositor will be added. Cannot be null.
clearColorColor?The color used to clear the screen. Defaults to CornflowerBlue if not specified.
msaaMultisampleCountMultisample anti-aliasing level. Defaults to None; use X4 when the scene draws thin geometry such as line meshes, which otherwise flickers as it moves. Clamped to what the device supports.
Returns
- GraphicsCompositor
The newly created GraphicsCompositor with post-processing effects enabled.
AddGroundGizmo(Game, Vector3?, bool, bool)
Adds a ground gizmo to the game's root scene, attached to an existing ground entity.
public static void AddGroundGizmo(this Game game, Vector3? position = null, bool showAxisName = false, bool rotateAxisNames = true)
Parameters
gameGameThe Game instance in which the ground gizmo will be added.
positionVector3?The position of the gizmo in 3D space. If null, the gizmo will be placed at the origin (0, 0, 0).
showAxisNameboolA boolean indicating whether the axis names (X, Y, Z) should be displayed on the gizmo. Default is false.
rotateAxisNamesboolA boolean indicating whether the axis names should rotate to always face the camera. Default is true.
Remarks
The gizmo is added as a child to an existing ground entity. If the ground entity is not found, the method will return without adding the gizmo. The gizmo helps visualize the ground with axis indicators in 3D space.
AddParticleRenderer(Game)
Adds particle rendering capabilities to the specified game.
public static void AddParticleRenderer(this Game game)
Parameters
gameGameThe game to which particle rendering stages and features will be added. Cannot be null.
Remarks
This method extends the game's graphics compositor by incorporating stages and features necessary for rendering particles. Ensure that the game has a valid scene system before invoking this method.
AddProfiler(Game, string?)
Adds a profiler to the game, which can be toggled on/off with Left Shift + Left Ctrl + P and provides other keyboard shortcuts. Changing the filtering mode with F1, altering the sorting mode with F2, navigating result pages with F3 and F4, and adjusting the refresh interval with the plus and minus keys.
public static Entity AddProfiler(this Game game, string? entityName = "Game Profiler")
Parameters
gameGameThe game to which the profiler will be added.
entityNamestringOptional name for the entity to which the GameProfiler script will be attached.
Returns
- Entity
The entity to which the GameProfiler script was attached.
Remarks
This extension method creates an entity and attaches a GameProfiler script to it, enabling in-game profiling. The profiler's behavior can be interacted with using various keyboard shortcuts as described in the GameProfiler class.
AddRootRenderFeature(Game, RootRenderFeature)
Adds a root render feature to the game's graphics compositor.
public static void AddRootRenderFeature(this Game game, RootRenderFeature renderFeature)
Parameters
gameGameThe game instance to which the render feature will be added. Cannot be null.
renderFeatureRootRenderFeatureThe root render feature to add. Cannot be null.
AddSceneRenderer(Game, SceneRendererBase)
Adds a scene renderer to the game's GraphicsCompositor.
public static void AddSceneRenderer(this Game game, SceneRendererBase renderer)
Parameters
gameGameThe Game instance to add the renderer to.
rendererSceneRendererBaseThe scene renderer to be added, inheriting from SceneRendererBase.
Exceptions
- ArgumentNullException
Thrown when the
rendereris null.- InvalidOperationException
Thrown if the GraphicsCompositor is not set in the game's SceneSystem.
AddStudioLighting(Game, float, float, bool, bool)
Adds a three-point studio lighting rig - key, fill and rim - aimed at the scene's centre.
public static (Entity Key, Entity Fill, Entity Rim) AddStudioLighting(this Game game, float intensity = 15, float yawDegrees = 45, bool enableShadows = true, bool showLightGizmo = false)
Parameters
gameGameThe game instance to which the lighting will be added.
intensityfloatThe key light's intensity. The fill and rim are derived from it. Default is 15.
yawDegreesfloatHorizontal direction the rig faces, in degrees about the world Y axis. The default of 45 faces the toolkit's default camera at (6, 6, 6); pass the yaw of your own camera to swing the whole rig around with it.
enableShadowsboolWhether the key light casts shadows. Only the key ever does. Default is true.
showLightGizmoboolWhether to show a gizmo for each light. Default is false.
Returns
- (Entity Key, Entity Fill, Entity Rim)
The three light entities - key, fill and rim - for further adjustment.
Remarks
This is the photographer's rig: a bright key light from high on one side of the camera gives every surface its main shading and the scene its shadows; a dim fill from low on the other side lifts the key's shadows so they read as shadow rather than black; and a rim from high behind the subject traces a bright edge along silhouettes, separating objects from the background. Because the three intensities differ, curved and angled surfaces shade differently on every face - which is what makes shapes look solid.
Compare AddAllDirectionLighting(Game, float, bool), which lights evenly from all six axes: nothing is ever dark, but everything is lit the same, so shape flattens. Prefer the studio rig for showing off models and lettering; prefer all-direction lighting when reading a surface's colour matters more than reading its form, as on a game board of colour-coded cubes.
Directional lights ignore position, so the rig works whatever the scene's scale; positions are set anyway so the gizmos hover where each light conceptually sits.
AddWorldTextRenderer(Game)
Registers the renderer that draws WorldTextComponent, once, however many times this is called.
public static void AddWorldTextRenderer(this Game game)
Parameters
gameGameThe game whose compositor the renderer is added to.
Remarks
A WorldTextComponent without this renderer simply never appears - no error, no log line, just absent text - so call this whenever world text is used. Helpers that create world text themselves, such as AddGroundGizmo(Game, Vector3?, bool, bool) with axis names, call it on your behalf; calling it again is harmless, because a duplicate renderer is not added.
Exceptions
- InvalidOperationException
Thrown if the GraphicsCompositor is not set in the game's SceneSystem.
ConfigurePostEffects(Game, Action<PostProcessingEffects>)
Configures the post effects of the game's current compositor.
public static Game ConfigurePostEffects(this Game game, Action<PostProcessingEffects> configure)
Parameters
gameGameThe game.
configureAction<PostProcessingEffects>Receives the live PostProcessingEffects.
Returns
- Game
The game, for chaining.
Remarks
See ConfigurePostEffects(GraphicsCompositor, Action<PostProcessingEffects>) for what is on by default (nothing but tone mapping) and what must be added rather than enabled.
Exceptions
- ArgumentNullException
gameorconfigureis null.- InvalidOperationException
The game has no compositor, or its compositor has no post effects.
Create2DPrimitive(IGame, Primitive2DModelType, Primitive2DEntityOptions?)
Creates an entity with a 2D procedural primitive model of the specified type.
public static Entity Create2DPrimitive(this IGame game, Primitive2DModelType type, Primitive2DEntityOptions? options = null)
Parameters
gameIGameThe IGame instance used to access game services.
typePrimitive2DModelTypeThe 2D primitive type to create.
optionsPrimitive2DEntityOptionsOptional creation parameters, including size, custom polygon vertices, depth, material, render group, entity name, and position. If null, default options are used.
Returns
- Entity
A new Entity with a ModelComponent containing the generated primitive model.
Remarks
The returned entity is not added to a scene automatically. Assign it to a scene before rendering.
If a material is specified in options, it is added to the generated model's material collection.
If no size is specified for capsules or rectangles, this method applies default dimensions before building the model.
The Depth option controls the generated mesh thickness along the Z axis.
Exceptions
- ArgumentNullException
Thrown when
gameis null.
Create3DPrimitive(IGame, PrimitiveModelType, Primitive3DEntityOptions?)
Creates an entity with a 3D procedural primitive model of the specified type.
public static Entity Create3DPrimitive(this IGame game, PrimitiveModelType type, Primitive3DEntityOptions? options = null)
Parameters
gameIGameThe IGame instance used to access game services.
typePrimitiveModelTypeThe 3D primitive type to create.
optionsPrimitive3DEntityOptionsOptional creation parameters, including size, material, render group, entity name, and position. If null, default options are used.
Returns
- Entity
A new Entity with a ModelComponent containing the generated primitive model.
Remarks
The returned entity is not added to a scene automatically. Assign it to a scene before rendering.
If a material is specified in options, it is added to the generated model's material collection.
Exceptions
- ArgumentNullException
Thrown when
gameis null.
CreateEmissiveMaterial(IGame, Color, float)
Creates a material that gives off its own light: a lamp, a sign, a glowing edge. Above an intensity of 1 the colour overshoots the display range, which is what a bloom post effect picks out of the frame.
public static Material CreateEmissiveMaterial(this IGame game, Color color, float intensity = 1)
Parameters
gameIGameThe game instance used to access the graphics device.
colorColorThe colour, lit and emitted.
intensityfloatThe emissive strength; 1 is the colour as given, 5 or more blooms under post effects.
Returns
- Material
A new material instance.
CreateFlatMaterial(IGame, Color?)
Creates a material with flat colors ideal for 2D rendering, using emissive color unaffected by lighting.
public static Material CreateFlatMaterial(this IGame game, Color? color = null)
Parameters
gameIGameThe game instance used to access the graphics device.
colorColor?The color of the material, including alpha. Uses white if not specified.
Returns
- Material
A new material instance with flat coloring.
CreateMaterial(IGame, MaterialDescriptor)
Compiles a descriptor into a material with the game's content manager, so the engine's lookup-table
environment term resolves, and keeps the descriptor on it, so the material can be used as a
MaterialBlendLayer later: Material.New leaves
Descriptor null, and the generator composes a layer from its features.
public static Material CreateMaterial(this IGame game, MaterialDescriptor descriptor)
Parameters
gameIGameThe game instance used to access the graphics device.
descriptorMaterialDescriptorThe bag of features: one from MaterialDescriptors with something added, or your own.
Returns
- Material
The compiled material, its descriptor attached.
CreateMaterial(IGame, Color?, float, float)
Creates a PBR (physically based rendering) material from a colour, a metalness and a glossiness, under the Lambert diffuse and microfacet specular models.
public static Material CreateMaterial(this IGame game, Color? color = null, float metalness = 0, float glossiness = 0.65)
Parameters
gameIGameThe game instance used to access the graphics device.
colorColor?The colour. Defaults to null, which uses DefaultMaterialColor.
metalnessfloat0 for a dielectric, which keeps its colour as diffuse and reflects a colourless 4 percent; 1 for a metal, which has no diffuse and reflects in its own colour. Defaults to 0, a matte coloured surface.
glossinessfloat0 for rough, where the highlight is a haze; 1 for a mirror. Defaults to 0.65f.
Returns
- Material
A new material instance with the specified or default attributes.
Remarks
Compiles Pbr(Color, float, float) with the game's content manager, so the specular model's
lookup-table environment term resolves; Material.New without it leaves the table empty and every metal
renders black. A colour alone gives a dielectric; ask for a metal explicitly. When the material is nearly
right but needs one more feature, take the descriptor from MaterialDescriptors, add to it,
and compile it with CreateMaterial(IGame, MaterialDescriptor). The manual page on materials
explains what the numbers claim.
CreateOverlayMaterial(IGame, Color, float)
Creates an unlit translucent material: a zone, a placement preview, a selection volume, a marker drawn over the scene. The colour's alpha is the opacity, and no light touches it.
public static Material CreateOverlayMaterial(this IGame game, Color color, float intensity = 1)
Parameters
gameIGameThe game instance used to access the graphics device.
colorColorThe colour, with its alpha as the opacity. 255 is opaque.
intensityfloatThe emissive strength; 1 is the colour as given, more than 1 blooms under post effects.
Returns
- Material
A new material instance.
CreateScreenMaterial(IGame, Texture, float)
Creates the material for a screen showing a texture, such as a monitor showing a render-texture camera's feed or a poster: unlit and clamped at the edges, so the picture reads as given whichever way the surface faces.
public static Material CreateScreenMaterial(this IGame game, Texture texture, float intensity = 1)
Parameters
gameIGameThe game instance used to access the graphics device.
textureTextureWhat the screen shows; a render target works as well as a loaded image.
intensityfloatThe emissive strength; 1 shows the texture's own colours.
Returns
- Material
A new material instance.
CreateTexturedMaterial(IGame, Texture, float, float, float)
Creates a material with a texture where the colour would be, tiled tiling times, with
the same metalness and glossiness as CreateMaterial(IGame, Color?, float, float).
public static Material CreateTexturedMaterial(this IGame game, Texture texture, float metalness = 0, float glossiness = 0.65, float tiling = 1)
Parameters
gameIGameThe game instance used to access the graphics device.
textureTextureThe albedo, loaded as a colour (sRGB) texture.
metalnessfloat0 for a dielectric, 1 for a metal.
glossinessfloat0 for rough, 1 for a mirror.
tilingfloatHow many times the texture repeats across the UV range.
Returns
- Material
A new material instance.
DeltaTime(IGame)
Gets the elapsed update time for the current frame, in seconds.
public static float DeltaTime(this IGame game)
Parameters
Returns
- float
The elapsed update time as a single-precision floating-point value.
Remarks
Use this value for frame-rate independent movement and animation. For calculations that need more precision, use DeltaTimeAccurate(IGame).
Exceptions
- ArgumentNullException
Thrown when
gameis null.
DeltaTimeAccurate(IGame)
Gets the elapsed update time for the current frame, in seconds, with double precision.
public static double DeltaTimeAccurate(this IGame game)
Parameters
Returns
- double
The elapsed update time as a double-precision floating-point value.
Remarks
This method returns the same elapsed update interval as DeltaTime(IGame), but avoids conversion to float.
Exceptions
- ArgumentNullException
Thrown when
gameis null.
DisableVSync(IGame)
Sets the presentation interval to present frames immediately.
public static void DisableVSync(this IGame game)
Parameters
Remarks
This method sets PresentInterval to Immediate.
Immediate presentation can improve responsiveness, but may cause visible tearing.
Exceptions
- ArgumentNullException
Thrown when
gameis null.
EnableVSync(IGame)
Sets the presentation interval to wait for every second vertical blank.
public static void EnableVSync(this IGame game)
Parameters
Remarks
This method sets PresentInterval to Two.
Waiting for vertical blanks can reduce tearing, but may increase presentation latency and reduce the effective frame rate.
Exceptions
- ArgumentNullException
Thrown when
gameis null.
Exit(IGame)
Requests the game to exit.
public static void Exit(this IGame game)
Parameters
Remarks
Exceptions
- ArgumentNullException
Thrown when
gameis null.- ArgumentException
Thrown when
gameis not a GameBase instance.
FPS(IGame)
Gets the current update frame rate, in frames per second.
public static float FPS(this IGame game)
Parameters
Returns
- float
The current frame rate as a floating-point value.
Remarks
This value is provided by UpdateTime and can be used for diagnostics, performance overlays, or gameplay-independent monitoring.
Exceptions
- ArgumentNullException
Thrown when
gameis null.
GetCameraEntity(Game, string?)
Gets the camera entity by name from the game's root scene.
public static Entity GetCameraEntity(this Game game, string? cameraName = "Main")
Parameters
gameGameThe game whose root scene is searched.
cameraNamestringThe camera entity's name. Defaults to the main camera name.
Returns
- Entity
The camera entity.
Remarks
The escape hatch for anything SetCameraPosition(Game, Vector3, string?) and SetCameraRotation(Game, Vector3, string?) do not cover - reading the transform, attaching a component, or replacing the camera outright.
Exceptions
- InvalidOperationException
No entity with that name exists in the root scene.
GetPostEffects(Game)
The post effects of the game's current compositor, or null when there are none.
public static PostProcessingEffects? GetPostEffects(this Game game)
Parameters
gameGameThe game.
Returns
Remarks
The runtime half of ConfigurePostEffects(Game, Action<PostProcessingEffects>): toggle an effect on a key press with
game.GetPostEffects()?.Bloom.Enabled ^= true.
Exceptions
- ArgumentNullException
gameis null.
LoadSystemFont(Game, string, float, FontStyle, string?)
Loads a font installed on the machine, ready to hand to any component that takes a SpriteFont.
public static SpriteFont? LoadSystemFont(this Game game, string family, float size, FontStyle style = FontStyle.Regular, string? fontFile = null)
Parameters
gameGameThe game whose services provide Stride's font system.
familystringThe family name as the system knows it, such as
"Segoe UI".sizefloatThe height the glyphs are rasterised at, in pixels.
styleFontStyleThe weight and slant wanted. Defaults to Regular.
fontFilestringA TrueType file to load the family from, for fonts outside the system font folders.
Returns
- SpriteFont
The font, or null if the family is not installed.
Remarks
A code-only game has no compiled font assets, so this is how it gets any font other than Stride's default one. Load each font once and keep it - see SystemFonts, which this forwards to and which can also try a list of families in order.
Run(Game, Action<Scene>?, Action<Scene, GameTime>?, GameContext?)
Starts the game loop, calling start once the root scene exists and
update on every frame after that.
public static void Run(this Game game, Action<Scene>? start = null, Action<Scene, GameTime>? update = null, GameContext? context = null)
Parameters
gameGameThe game to run.
startAction<Scene>Called once, with the root scene, before the first
update. Optional.updateAction<Scene, GameTime>Called every frame with the current root scene and the current UpdateTime. The scene is read fresh each frame, so after a scene switch it is the new root scene. Optional.
contextGameContextThe windowing context to run in - a host control to render into, a fixed initial size, an SDL or headless backend. Leave null to let the engine pick the platform default.
Examples
using var game = new Game();
game.Run(start: Start, update: Update);
void Start(Scene rootScene) => game.SetupBase3DScene();
void Update(Scene rootScene, GameTime time) { /* per frame */ }
Remarks
The engine creates the root scene only inside Run(GameContext), so
scene setup cannot happen before this call. Run schedules a script that invokes
start on the first frame, then loops update once per frame
until the game exits. Both callbacks run on the game thread, inside the script system, with
the same timing and exception behaviour as a StartupScript or SyncScript:
an exception thrown by either one propagates out of this method.
start may be asynchronous - see the Run(Game, Func<Scene, Task>, Action<Scene, GameTime>?, GameContext?)
overload. update is deliberately synchronous: it is the per-frame callback, and
anything that needs to await across frames belongs in an async start that runs
its own loop.
Exceptions
- ArgumentNullException
gameis null.
Run(Game, Func<Scene, Task>, Action<Scene, GameTime>?, GameContext?)
Starts the game loop with an asynchronous start: the update loop begins only
after the returned task completes.
public static void Run(this Game game, Func<Scene, Task> start, Action<Scene, GameTime>? update = null, GameContext? context = null)
Parameters
gameGameThe game to run.
startFunc<Scene, Task>Called once with the root scene; the update loop starts when its task completes.
updateAction<Scene, GameTime>Called every frame with the current root scene and the current UpdateTime. The scene is read fresh each frame, so after a scene switch it is the new root scene. Optional.
contextGameContextThe windowing context to run in. Leave null to let the engine pick the platform default.
Examples
using var game = new Game();
game.Run(start: async rootScene =>
{
game.SetupBase3DScene();
await game.Script.Delay(3); // countdown, splash, loading...
SpawnPlayer(rootScene);
}, update: Update);
Remarks
start runs as a script, so it can wait on the script system between steps -
await game.Script.NextFrame() to let physics attach, or
Delay(ScriptSystem, float) for a countdown - without writing
a StartupScript or AsyncScript class. A start that never
completes is valid, and is how to write a per-frame loop that also awaits: the same idiom as
Execute().
C# binds an async lambda or a Task-returning method group to this overload
and a synchronous one to Run(Game, Action<Scene>?, Action<Scene, GameTime>?, GameContext?),
so an async start is never silently compiled as async void.
Exceptions
- ArgumentNullException
gameorstartis null.
SetCameraPosition(Game, Vector3, string?)
Moves the existing camera to a new position, leaving its rotation alone.
public static Entity SetCameraPosition(this Game game, Vector3 position, string? cameraName = "Main")
Parameters
gameGameThe game whose camera is moved.
positionVector3The new world position.
cameraNamestringThe camera entity's name. Defaults to the main camera name.
Returns
- Entity
The camera entity, so calls can be chained.
Remarks
For adjusting the camera that SetupBase3DScene has already created. Calling
Add3DCamera(Game, string?, Vector3?, Vector3?, CameraProjectionMode) a second time is not the way to do it: that method builds a
new entity, binds it to camera slot 0 and adds it to the root scene, leaving two camera
entities competing for one slot.
Paired with SetCameraRotation(Game, Vector3, string?) rather than folded into one call, so that each line of an example says exactly what it does.
Exceptions
- InvalidOperationException
No camera entity with that name exists in the root scene.
SetCameraRotation(Game, Vector3, string?)
Rotates the existing camera, leaving its position alone.
public static Entity SetCameraRotation(this Game game, Vector3 rotation, string? cameraName = "Main")
Parameters
gameGameThe game whose camera is rotated.
rotationVector3The rotation in degrees, packed as
X = Yaw,Y = Pitch,Z = Roll- the same convention Add3DCamera(Game, string?, Vector3?, Vector3?, CameraProjectionMode) uses for itsinitialRotation, and the order the camera controller's F2 panel prints.cameraNamestringThe camera entity's name. Defaults to the main camera name.
Returns
- Entity
The camera entity, so calls can be chained.
Remarks
Yaw/pitch/roll rather than a quaternion because these numbers are meant to be read off the screen and typed back in. See SetCameraPosition(Game, Vector3, string?) for why this is not Add3DCamera(Game, string?, Vector3?, Vector3?, CameraProjectionMode).
Exceptions
- InvalidOperationException
No camera entity with that name exists in the root scene.
SetFocusLostFPS(IGame, int)
Sets the update interval used while the window is minimized, or unfocused when TreatNotFocusedLikeMinimized is set.
public static void SetFocusLostFPS(this IGame game, int targetFPS)
Parameters
gameIGameThe IGame instance to configure.
targetFPSintThe target update rate, in frames per second, used to calculate the minimized update interval. Must be greater than 0.
Remarks
This method configures MinimizedMinimumUpdateRate and is useful for reducing resource usage while the game is minimized.
The game instance must be a GameBase implementation.
Exceptions
- ArgumentNullException
Thrown when
gameis null.- InvalidCastException
Thrown when
gameis not a GameBase instance.
SetMaxFPS(IGame, int)
Sets the minimum update interval used while the game window is active.
public static void SetMaxFPS(this IGame game, int targetFPS)
Parameters
gameIGameThe IGame instance to configure.
targetFPSintThe target update rate, in frames per second, used to calculate the active-window update interval. Must be greater than 0.
Remarks
This method configures WindowMinimumUpdateRate and can be used to limit the update rate while the game is running normally.
The game instance must be a GameBase implementation.
Exceptions
- ArgumentNullException
Thrown when
gameis null.- InvalidCastException
Thrown when
gameis not a GameBase instance.
SetWindowSize(Game, int, int)
Sets the size the window opens at, in pixels. Call it before Run; once the device exists
the window is the user's to resize.
public static void SetWindowSize(this Game game, int width, int height)
Parameters
gameGameThe game whose window to size.
widthintThe width in pixels.
heightintThe height in pixels.
Remarks
The engine's default is 1280 by 720. An example whose scene is drawn in world units under a pixel-sized overlay - the easing sheet, with its twelve-line help block - gets more room from a taller window than from a smaller scene, so it opens a step larger. On a scaled display the window still opens at this many physical pixels: the size is the back buffer's, not the desktop's.
The engine creates the window at the device manager's preferred back-buffer size, which its
PrepareContext resets to the default just before - with AutoLoadDefaultSettings
on, which it is by default. So neither a GameContext with a requested size nor
PreferredBackBufferWidth set before Run survives, and RenderingSettings put
back afterwards are clamped to the window already made: that route can shrink a window but never
grow it. Resizing the window later - at WindowCreated, or from a startup
script with game.Window.SetSize as the Stride manual shows - works, but the window has
been resized after its handle was made and shows the old outline for its first few milliseconds.
This turns AutoLoadDefaultSettings off instead, so the size set through
UseGameSettings(Game, Action<GameSettings>?) stands and the window is created at it.
What the flag would otherwise have supplied from the same defaults - the graphics profile and
the colour space - UseGameSettings applies too, so nothing else changes. An example that
already mirrors a Game Studio project's settings can keep doing that for everything else; this
is the one line for the window.
Exceptions
- InvalidOperationException
Thrown when the game is already running.
SetupBase2D(Game, Color?)
Configures the game for 2D rendering by setting up the necessary graphics compositor and camera.
public static void SetupBase2D(this Game game, Color? clearColor = null)
Parameters
gameGameThe game instance to configure for 2D rendering.
clearColorColor?The color used to clear the screen. Defaults to CornflowerBlue if not specified.
SetupBase3D(Game)
Sets up essential components for the game, including a GraphicsCompositor, a camera, and a directional light.
public static void SetupBase3D(this Game game)
Parameters
gameGameThe Game instance that will receive the base setup.
Remarks
This method performs the following operations:
- Adds a default GraphicsCompositor to the game's SceneSystem and applies a clean UI stage.
- Adds a camera to the game.
- Adds a directional light to the game.
TakeScreenShot(IGame, string, ImageFileType)
Saves a screenshot of the current frame to the specified file path.
public static void TakeScreenShot(this IGame game, string fileName, ImageFileType fileType = ImageFileType.Png)