If you want to use a replacement shader, then use a replacement shader. However I wonder if that is actually what you want. If you’re getting the result you want from the current code, then that’s more likely already doing everything correctly.
The comments you have in the above script don’t make any sense. They might as well be:
Camera.main.targetTexture = mainRenderTexture; // add two eggs and mix until smooth
The comment you have is just as equally related as that.
Imagine you have several different sheets of paper. By default, if you do nothing, Unity is going to paint the scene onto a regular letter size sheet and then show that to you. Using that metaphor, this is what’s happening with your code.
// Hey Unity, before you paint anything I have some things I want you to do
void OnPreRender()
// take an older piece of paper and cut it down to the size you want
mainRenderTexture= RenderTexture.GetTemporary(width,height,16);
// tell Unity to use your piece of paper rather than the one it has
Camera.main.targetTexture = mainRenderTexture;
// Unity then paints the scene to your paper
// Hey Unity, after you finish painting everything, I have some things I want you to do
void OnPostRender()
// go back to your original piece of paper
Camera.main.targetTexture = null;
// while the paint is wet, just slap the paper you just painted onto your original paper to make a copy
// if they're not the same size, just kind of smear the paint around a bit to get it to fit
Graphics.Blit(mainRenderTexture,null as RenderTexture);
// now throw away the paper I gave you
RenderTexture.ReleaseTemporary(mainRenderTexture);
// Unity now shows the original piece of paper to you
At no point in any of that did you tell Unity to paint the objects differently, just to a different piece of paper.
If you want to change the shader the objects render with, then you want to use a replacement shader, or manually override the material / shader on your objects.
If you want to render to a different render texture, and use a replacement shader, you can do that. But you don’t need to use OnPreRender / OnPostRender (though you can). You could just do:
void Update()
{
tempTexture = RenderTexture.GetTemporary(width, height, 16);
camera.targetTexture = tempTexture;
camera.RenderWithShader(replacementShader, "RenderType");
}
Though in that example the output of the replacement shader will never be seen by you as it’s not ever getting copied to the frame buffer (what you screen is actually displaying, and what that Blit
to a null
in your code is doing).
You could also just do:
void Start()
{
camera.SetReplacementShader(replacementShader, "RenderType");
}
And nothing else. But I highly doubt that’s what you want.