Adding a Texture at Runtime
In this tutorial, we will explore how to dynamically apply a texture to a 3D object in your Stride project. By using the Texture
class, you can load an image file at runtime and assign it to a 3D entity. We will demonstrate how to do this by applying a texture to a cube.
What You'll Learn
- How to load a texture from an image file at runtime.
- How to create and configure a
MaterialDescriptor
to apply the texture to a 3D object. - How to create a 3D primitive (cube) and assign the texture as its material.
Code Walkthrough
using Stride.CommunityToolkit.Bullet;
using Stride.CommunityToolkit.Engine;
using Stride.CommunityToolkit.Rendering.ProceduralModels;
using Stride.Core.Mathematics;
using Stride.Engine;
using Stride.Graphics;
using Stride.Rendering;
using Stride.Rendering.Materials;
using Stride.Rendering.Materials.ComputeColors;
using var game = new Game();
game.Run(start: Start);
void Start(Scene scene)
{
// Set up a base 3D scene with default lighting and camera
game.SetupBase3DScene();
// Load the texture from a file
var texturePath = "Stride-logo.png";
using var textureFile = File.Open(texturePath, FileMode.Open);
var texture = Texture.Load(game.GraphicsDevice, textureFile);
// Create a material descriptor and assign the loaded texture to it
var materialDescriptor = new MaterialDescriptor
{
Attributes =
new MaterialAttributes
{
Diffuse = new MaterialDiffuseMapFeature(new ComputeTextureColor(texture)),
// Configures using the Lambert lighting model,
// which simulates how light interacts with the surface
DiffuseModel = new MaterialDiffuseLambertModelFeature(),
// Specifies the back-face culling mode
CullMode = CullMode.Back
}
};
// Create a material instance from the descriptor
var material = Material.New(game.GraphicsDevice, materialDescriptor);
// Create a 3D cube primitive and assign the material to it
var entity = game.Create3DPrimitive(PrimitiveModelType.Cube, new()
{
Material = material,
});
entity.Transform.Position = new Vector3(0, 8, 0);
// Add the cube to the root scene
entity.Scene = scene;
}
Running the Code
When you run this code, the game will display a 3D cube with the specified texture applied to its surface. The texture will be visible, and the cube will be placed 8 units above the ground.
Summary
This example demonstrates how to dynamically load and apply a texture to a 3D object at runtime in Stride. The process involves:
- Loading a texture from an image file.
- Creating a material to define how the texture should be rendered.
- Applying the material to a 3D primitive and adding it to the scene.
This approach can be extended to various other 3D models and textures, allowing you to dynamically change the appearance of objects in your game.