前言
RenderTexture 真是令人又爱又恨,实际用到项目中是问题是一波接着一波地来啊!
以下是在 Unity 中与它鏖战数月的经验……都在这里了!收下吧!!这是我最后的总结了!!!
RenderTexture 通常用来将 3D 模型转为 2D图片,从而在UI中使用,一般会用来做人物、装备、物品预览界面。
问题一、震惊!粒子特效在 RenderTexture 中无法显示!
这里首先我们想用 RenderTexture 显示个球,这里 RenderTexture 相机背景色设透明,场景主相机背景灰色:
然后在球边上加个简陋的粒子特效:
发现 RenderTexture 里的粒子特效根本不显示!还是只有个球!
什么?! 大名鼎鼎,如雷贯耳的 RenderTexture 竟然连如此简陋的粒子特效都显示不了?真是天大的笑话!
发现粒子其实是只在球体范围内显示,我们把球的颜色换成黑色,粒子多一点,可以看得更清楚:
RenderTexture 相机背景色设为透明后,似乎就把模型周围的所有像素剔除了,这该如何是好?
解决方案: 这一切都是 ColorMask 的错!
我们将官方 Particle Add/Blend Shader 进行改造,将 ColorMask RGB 改为 ColorMask RGBA 即可。以下是改后的 Shader,想用可自取:
Shader "Custom/Additive For RT"
{
Properties {
_TintColor ("Tint Color", Color) = (0.5,0.5,0.5,0.5)
_MainTex ("Particle Texture", 2D) = "white" {}
}
Category {
Tags { "Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent" "PreviewType"="Plane" }
Blend SrcAlpha One
ColorMask RGBA
Cull Off Lighting Off ZWrite Off
SubShader {
Pass {
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma target 2.0
#include "UnityCG.cginc"
sampler2D _MainTex;
fixed4 _TintColor;
struct appdata_t {
float4 vertex : POSITION;
fixed4 color : COLOR;
float2 texcoord : TEXCOORD0;
UNITY_VERTEX_INPUT_INSTANCE_ID
};
struct v2f {
float4 vertex : SV_POSITION;
fixed4 color : COLOR;
float2 texcoord : TEXCOORD0;
UNITY_VERTEX_OUTPUT_STEREO
};
float4 _MainTex_ST;
v2f vert (appdata_t v)
{
v2f o;
UNITY_SETUP