Unreal Engine - How to prepare a shader directory in your plugin

Unreal Engine - How to prepare a shader directory in your plugin

Created
Jan 2, 2024 02:24 PM
Tags

Introduction

In this article I would like to show you how to prepare a shader directory when you want to implement shaders in a plugin. The code is based on 4.26.2.

Implementation

First, we will create a blank plugin in Unreal Engine.
notion image
In this tutorial I would name my plugin ‘EmptyPlugin’. Remember to replace it with your plugin name when copying the code. We need to change the “Loading Phase” in the EmptyPlugin.uplugin file to the values shown in the image.
notion image
The reason
Shaders need to be compiled before the engine initialization, since the engine needs to cache all shaders for rendering purpose. We will cover this in the upcoming Shader Compilation article.
Then we will create a new folder called ‘Shaders’. You can name it whatever you want. ‘Shaders’ the name that is commonly used in Unreal Engine.
notion image
In EmptyPlugin.cpp, find the StartModule() function, and add the code below. FindPlugin() here is to find the relative path. AddShaderSourceDirectoryMapping() is straightforward. The first parameter is the virtual path that you will use in your shader files, the second parameter is the absolute path we resolved using the line above.
notion image
To use this, simply include the file inside your virtual path.
/MyShaderDir/MyShader.usf
Finally, do not forget to add required dependencies in EmptyPlugin.build.cs.
notion image
Now you can freely use your code in your plugin.
 
The official guide is here.
Â