---
title: "Choose an HLSL texture and sampler at runtime"
url: https://recursiveai.org/oneshader/cookbook/choose-hlsl-texture-and-sampler-at-runtime/
description: "Use an HLSL runtime flag to choose one of two fixed texture and sampler pairs. Compile to SPIR-V, Metal, and WGSL without bindless resources."
version: "1.7.3"
---

# Choose an HLSL texture and sampler at runtime

**OneShader** is a free, open-source HLSL compiler library for .NET from Recursive AI. MIT or Apache-2.0.

[NuGet](https://www.nuget.org/packages/RecursiveAI.OneShader) · [GitHub](https://github.com/recursive-ai-oss/oneshader-csharp) · [Docs](https://recursiveai.org/oneshader/docs/) · [Download example (.zip)](https://recursiveai.org/oneshader/cookbook/choose-hlsl-texture-and-sampler-at-runtime/choose-hlsl-texture-and-sampler-at-runtime.zip)

Use a runtime flag to switch between two fixed texture and sampler pairs.

```shell
dotnet add package RecursiveAI.OneShader
```

Requires [.NET 10](https://dotnet.microsoft.com/download/dotnet/10.0) (net10.0); .NET 9 and earlier aren’t supported.

```hlsl
Texture2D<float4> tex = UseNight ? Night : Day;
SamplerState filter = UseNight
    ? Nearest : Linear;
return tex.SampleLevel(filter, uv, 0);
```

This is the body of the pixel shader in `Choose.hlsl` below. It declares the resources and the `UseNight` flag; `uv` is the pixel shader’s texture coordinate. The example writes `choose.spv`, `choose.metal`, and `choose.wgsl`.

[The example](https://recursiveai.org/oneshader/cookbook/choose-hlsl-texture-and-sampler-at-runtime/choose-hlsl-texture-and-sampler-at-runtime.zip) is the full program below: unzip it and `dotnet run`.

## Full program

Save this input as `Choose.hlsl` beside `Program.cs`, or use the copy in the zip.

```hlsl
Texture2D<float4> Day : register(t0);
Texture2D<float4> Night : register(t1);
SamplerState Linear : register(s2);
SamplerState Nearest : register(s3);
cbuffer Settings : register(b4) { uint UseNight; };

[shader("pixel")]
float4 PSMain(float2 uv : TEXCOORD0) : SV_Target
{
    Texture2D<float4> tex = UseNight ? Night : Day;
    SamplerState filter = UseNight
        ? Nearest : Linear;
    return tex.SampleLevel(filter, uv, 0);
}
```

```csharp
using OneShader;

var result = ShaderCompiler.CompileFile("Choose.hlsl",
    new CompileOptions { Targets = [CompileTarget.SpirV, CompileTarget.Msl, CompileTarget.Wgsl] });
if (!result.Success)
    throw new InvalidOperationException(
        string.Join(Environment.NewLine, result.Diagnostics));

foreach (var (target, file) in new[] {
    (CompileTarget.SpirV, "choose.spv"),
    (CompileTarget.Msl, "choose.metal"),
    (CompileTarget.Wgsl, "choose.wgsl") })
{
    var shader = result.Find("PSMain", target)!;
    File.WriteAllBytes(file, shader.ToArray());
    Console.WriteLine($"Wrote {file}");
}
```

```text
Wrote choose.spv
Wrote choose.metal
Wrote choose.wgsl
```

`OSH0331` here means the choice uses an array index that isn’t known until
the shader runs. Choose between named textures and samplers instead.

## Variations

**Use an `if` instead of `?:`.** Replace the pixel shader body with this. Both resources are still selected from fixed candidates.

```hlsl
Texture2D<float4> tex = Day;
SamplerState filter = Linear;
if (UseNight != 0)
{
    tex = Night;
    filter = Nearest;
}
return tex.SampleLevel(filter, uv, 0);
```

## Related recipes

- [Bind a fixed-size HLSL texture array](https://recursiveai.org/oneshader/cookbook/bind-fixed-size-hlsl-texture-array/)
- [Compile HLSL to multiple targets](https://recursiveai.org/oneshader/cookbook/compile-hlsl-to-multiple-targets/)

## The short answer

In OneShader 1.7.3, initialize local `Texture2D` and `SamplerState` variables from named, fixed resources using `?:` or an `if`, then sample with the local variables. The runtime input here is `UseNight`: zero samples `Day` with `Linear`, and nonzero samples `Night` with `Nearest`. The C# example compiles the shader; it does not upload textures or render an image.

## How do you bind the textures a shader chooses at runtime?

Bind both candidates before drawing, even when the setting only selects one for a particular draw. In this Vulkan example, set 0 bindings 0 and 1 are the sampled images, 2 and 3 are the samplers, and 4 is the constant buffer that supplies `UseNight`. `Linear` and `Nearest` are just HLSL names. Create the sampler objects with the filtering you want in the application and put them in the corresponding bindings. The flag changes which pair the shader uses, not what is bound.

The candidates can be named resources or elements selected with constant indices. That differs from picking `Textures[index]` with a runtime index. OneShader lowers each use of a local choice to branches that refer to known bindings. That means a small fixed list needs no descriptor indexing just for making this choice. When you have a large resource table rather than two or three known options, use a resource array if the target and its binding model support the indexing you need.

## Can you call Sample after choosing a texture in a branch?

The emitted sampling instructions are inside branches too. [`Sample`](https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-to-sample) uses implicit derivatives for mip selection, so a choice that varies across neighboring fragments can cause derivative-uniformity problems. A constant-buffer flag that is the same for the draw avoids that kind of per-fragment variation. The example uses [`SampleLevel`](https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-to-samplelevel) explicitly at mip level 0, so it doesn’t need implicit derivatives. If you need automatic mip selection, keep the resource choice uniform where the sample executes.
