Adding a Texture at Runtime
This tutorial shows how to dynamically apply a texture to a 3D object in your Stride project. Using the Texture
class, you'll load an image at runtime and assign it to a 3D entity (a cube).
What you'll learn
- Load a texture from an image file at runtime.
- Create and configure a
MaterialDescriptor
to apply the texture. - Create a 3D primitive (cube) and assign the material.
Code walkthrough
using Stride.CommunityToolkit.Bepu;
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, you'll see a 3D cube with the specified texture applied. The cube is placed 8 units above the ground.
Summary
- Load a texture from an image file.
- Create a material that uses the texture.
- Apply the material to a 3D primitive and add it to the scene.
You can apply the same approach to other models and textures to change object appearance at runtime.