- Home /
Static GameObjects Losing Normal On Play
Please, someone help! I'm loosing my mind over this...
Parented to my MainCam I have another camera (CopyCam) with the same params, local transform equal to Identity and the Camera Component disabled. On my MainCam I added a script that, at OnRenderImage, calls RenderWithShader on the CopyCam with a shader that renders the fragments normals as RGB. The CopyCam.targetTexture is assigned as a RenderTexture (serialized RenderTexture that gets a temporary render texture when the screen changes size). All works fine, and the generated texture looks correct (left image), but when I hit play, some of the normals goes missing (right image):
Did some digging and found that this only happens when my GameObjects are marked as static. WHY!? Is this a setting? Can I have them as static and keep the normals correct?
Answer by Bunny83 · May 26, 2018 at 12:52 AM
This is most likely an issue with the shader you're using. Keep in mind that static gameobjects are statically batched. So they will be combined into a single gameobject and rendered as a single object. So the origin and local to world matrix will be different from those of the original objects.
Thanks for replying so quickly! So, this is my replacement shader:
Shader "ReplacementShader/NormalAndDepth"
{
SubShader
{
Tags { "RenderType"="Opaque" }
LOD 100
Pass
{
CGPROGRA$$anonymous$$
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
struct appdata
{
float4 vertex : POSITION;
float3 normal : NOR$$anonymous$$AL;
};
struct v2f
{
float4 vertex : SV_POSITION;
float3 camPos : TEXCOORD0;
float3 normal : TEXCOORD1;
};
v2f vert (appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.camPos = UnityObjectToViewPos(v.vertex);
o.normal = v.normal;
return o;
}
fixed4 frag (v2f i) : SV_Target
{
return fixed4(normalize(i.normal).xyz, (-i.camPos.z * _ProjectionParams.w));
}
ENDCG
}
}
}
Am I doing something wrong?
You do not transform the normal from local to world space. You just use the local space normal. When the objects are batched all vertex parameters get a new local space and are transformed.
use
o.normal = UnityObjectToWorldNormal(v.normal);
ins$$anonymous$$d of
o.normal = v.normal;
Also it seems a bit weird that you call the other variable "camPos" as it doesn't represent the position of the camera but the position of the vertex in the localspace of the camera.
Thanks, it seems to be working now! And yes, its a typo, supposed to be viewPos. Again, thanks!
Your answer
![](https://koobas.hobune.stream/wayback/20220612163432im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Why is the CPU usage so high? 1 Answer
Complex Depth Shader 0 Answers
How to make transparent only colliding part of object? 0 Answers
Shading with GL.TRIANGLE_STRIP 2 Answers
Native rendering plugin D3D11 device type not being set in x86 builds. 0 Answers