This project demonstrates how to replace a Texture2D asset with another during an AssetBundle build using a custom IBuildTask in Unity's Scriptable Build Pipeline (SBP).
The core of this project is a Unity Editor test that builds AssetBundles for a simple prefab. The prefab (quad.prefab) uses a material (mat1.mat) which in turn uses a 32x32 texture (image1.png).
During the build process, a custom task (ReplaceTextureTask) intercepts the build pipeline and swaps image1.png with a different 4x4 texture (empty.png). The test then loads the resulting AssetBundles and verifies that the material on the instantiated prefab is using the replacement texture, confirming the swap was successful.
The replacement is achieved via the ReplaceTextureTask, a custom implementation of SBP's IBuildTask.
- Injection: The task is inserted into the default build task list just before the
WriteSerializedFilestask. - Object Remapping: It identifies the
ObjectIdentifierfor both the original and replacement textures. - Data Swap: Before the bundle data is written to disk, the task iterates through the
WriteOperationsand replaces theserializationObjectpointing to the original texture with the one for the replacement texture. - Result: The material's reference to the texture's object identifier remains unchanged, but the data associated with that identifier is now the replacement texture's data. When the bundle is loaded, the material uses the new texture.
The entire process is orchestrated and verified within a single NUnit test (Build_WithTextureReplacement_MaterialUsesReplacementTexture).
Assets/quad.prefab: A simple quad prefab with aMeshRenderer.Assets/mat1.mat: A material assigned to the quad, which usesimage1.png.Assets/image1.png: The original 32x32 opaque texture.Assets/empty.png: The replacement 4x4 transparent texture.Assets/Tests/Editor/AssetBundleReplaceTest.cs: Contains the two main classes:ReplaceTextureTask: The custom SBP build task that performs the texture swap.AssetBundleReplaceTest: The NUnit test fixture that drives the build, load, and verification process.
- Open the project in a compatible version of the Unity Editor.
- Wait for the project to compile.
- Open the Test Runner window via Window > General > Test Runner.
- In the Test Runner, select the EditMode tab.
- Click the Run All button or run the
Build_WithTextureReplacement_MaterialUsesReplacementTexturetest specifically.
The test will execute the following steps:
- Build two AssetBundles (
mat1_bundleandquad_bundle) into a temporary directory, replacingimage1.pngwithempty.pngduring the process. - Load the bundles and instantiate the
quad.prefab. - Assert that the
mainTextureon the quad's material has a width and height of 4, matching the dimensions ofempty.png. - Clean up by deleting the temporary directory and unloading all assets.
The test should pass, indicated by a green checkmark in the Test Runner, confirming the texture was successfully replaced at build time.