- Home /
Render Textures always appear on top?
Maybe this is how they're meant to work, but the Unity docs don't explicitly state so, so I'm wondering maybe I'm missing something.
I've been using a Camera Pixelate script I found online for a while on my Weapon Camera for my FPS game. It's been working great, but now that I've started to add UI elements I've noticed that camera renders the weapon over everything - including the HUD elements. I've played with the depth and sort order to no avail, so I'm wondering if it's just a genuine limitation, and if so what a better route would be.
The script originally used GUI.DrawTexture, however Googling suggested to use Graphics.DrawTexture instead. This has not made a difference.
CameraPixelate script:
public class WeaponCameraTest : MonoBehaviour
{
public RenderTexture renderTexture;
void Start()
{
int realRatio = Mathf.RoundToInt(Screen.width / Screen.height);
renderTexture.width = NearestSuperiorPowerOf2(Mathf.RoundToInt(renderTexture.width * realRatio));
Debug.Log("(Pixelation)(Start)renderTexture.width: " + renderTexture.width);
}
void OnGUI()
{
GUI.depth = 0;
Graphics.DrawTexture(new Rect(0, 0, Screen.width, Screen.height), renderTexture);
}
int NearestSuperiorPowerOf2(int n)
{
return (int)Mathf.Pow(2, Mathf.Ceil(Mathf.Log(n) / Mathf.Log(2)));
}
}
I thought the GUI.depth might've been the problem, but I've changed that to no avail. I also tried setting renderTexture.depth through code which doesn't appear to work.
And this is the Render Texture itself, although I've played with all the settings and observed no difference:
Maybe it's just my misunderstanding of how Render Textures work - if so is there a better solution I should be looking at? The purpose of this script is just to pixelate the weapon camera (e.g. the weapon being held in an FPS), but not the main camera.
Answer by Namey5 · Feb 28, 2021 at 09:22 PM
This doesn't really have anything to do with the RT - you are applying it via the IMGUI system, which will always be rendered on top of the scene (including UGUI). If you want it to draw before UI then the easiest way is to add it as a RawTexture underneath the rest of your HUD via the UGUI system.
This seems to be the right route - thank you!
For anyone stumbling across this in their Googling: I had to create a Canvas under the player object, put a Raw Image on it, and then use the same CameraPixelate RT that the camera was utilising as its target texture. I still had further issues of clipping, these seem to be related to the fact that I was using several canvases and the sort order of the Raw Image only seems to apply to the canvas it sits in (i.e. it was still displaying over other canvases regardless of depth setting). There may be a proper way around this, but in my case I was able to just consolidate all the canvases to resolve the issue.