- Home /
Run a shader once on a texture
I've found/made a gaussian blur shader which works perfectly, but the game runs a lot slower than without it. Since I want to use it for depth of field in 2d, it could just be applied once when the level starts. I've heard about Graphics.Blit but I have no idea how that works. I basically want to change the sprite to a blurred version of itself (via this blur shader I found for example). How can I do this?
Answer by Namey5 · Feb 17, 2021 at 07:51 AM
I would recommend pre-processing the textures outside of the game for a number of reasons - not only is it easier, but it also means many objects can reuse the same textures rather than creating new textures for every instance. If you really need to do this, then yes you can use Graphics.Blit to render into a RenderTexture then read that back to a Texture2D;
[SerializeField] private Shader m_Shader;
private Material m_Material;
public Texture2D BlurTexture (Texture2D a_SourceTex)
{
//Make sure we have a material
if (m_Material == null)
m_Material = new Material (m_Shader);
//Get a temporary RenderTexture and draw our source texture into it using our shader
RenderTexture tmp = RenderTexture.GetTemporary (a_SourceTex.width, a_SourceTex.height, 0);
Graphics.Blit (a_Source, tmp, m_Material);
//Store the last active RT and set our new one as active
RenderTexture lastActive = RenderTexture.active;
RenderTexture.active = tmp;
//Read the blurred texture into a new Texture2D
Texture2D blurTex = new Texture2D (tmp.width, tmp.height);
blurTex.ReadPixels (new Rect (0, 0, tmp.width, tmp.height), 0, 0);
blurTex.Apply ();
//Restore the last active RT and release our temp tex
RenderTexture.active = lastActive;
RenderTexture.ReleaseTemporary (tmp);
return blurTex;
}
Something along those lines. Note that this is meant for image effect/unlit shaders - things like surface shaders will probably turn out weird if they even work at all.
I acually pre-blurred them first, but I didn't really like it, since dynamic blur looks a lot better in my opinion. I can totally see the reusage of textures, so maybe I could make a script that checks at the start of a level if a texture with about the correct blur level already exists and if not creates a new texture. Thanks, you really helped me out with this blur thingy! EDIT: I tested it out now but apart from a long loading "lag" when the level loads it still runs very smoothly!
Your answer
Follow this Question
Related Questions
How do I stop my sprite from jumping in the air? 1 Answer
Making the enemy follow the path of the Player,How to make the enemy follow the path of the player? 0 Answers
2D Box Collider / Sprite change direction issue 1 Answer
Syncing SpriteRenderer’s Sprite Over Network 1 Answer
Image swapping sprites delay. 0 Answers