一個(gè)bug
最近正在做交接工作,被問(wèn)到了一個(gè)問(wèn)題,如下圖:
左邊這個(gè)球用的是Unity內(nèi)置的Standard shader,開(kāi)啟了紅色的自發(fā)光??梢钥吹?,烘培后,自發(fā)光照亮了地面。
右邊這個(gè)球用的是我們自定義的shader,在 Meta Pass 我們同樣設(shè)置了 Emission,并且為了調(diào)試,我們把 Albedo 設(shè)置成了純黑色,并且簡(jiǎn)化了自發(fā)光的計(jì)算,但是烘培的結(jié)果,自發(fā)光并未對(duì)地面產(chǎn)生影響。
half4 FragMeta (v2f i) : SV_Target
{
float2 mainUV = i.uvTex0;
half4 mainColor = tex2D(_MainTex, mainUV);
half3 emissionColor = mainColor.rgb * _EmissionColor.rgb * _EmissionFactor * mainColor.a;
half3 specularColor = mainColor.a * _SpecularFactor * _SpecularColor;
UnityMetaInput metaIN;
UNITY_INITIALIZE_OUTPUT(UnityMetaInput, metaIN);
metaIN.Albedo = mainColor * 0;
metaIN.Emission = _EmissionColor.rgb * _EmissionFactor;
metaIN.SpecularColor = specularColor;
return UnityMetaFragment(metaIN);
}
原因
搜了一下,發(fā)現(xiàn)也有人遇到了同樣的問(wèn)題,鏈接如下:
My Emissive Material/Shader Does Not Appear In The Lightmap.
文章給出了解決方案:如果是自定義的shader,我們需要特別設(shè)置一下材質(zhì)的GI屬性,代碼如下:
using UnityEngine;
using UnityEditor;
public class LightMapMenu : MonoBehaviour
{
// The menu item.
[MenuItem ("MyCustomBake/Bake")]
static void Bake ()
{
// Find all objects with the tag <Emissive_to_baked>
// We have to set the tag “Emissive_to_baked” on each GO to be baked.
GameObject[] _emissiveObjs = GameObject.FindGameObjectsWithTag("Emissive_to_baked");
// Then, by each object, set the globalIllumiationFlags to BakedEmissive.
foreach (GameObject tmpObj in _emissiveObjs)
{
Material tmpMaterial = tmpObj.GetComponent<Renderer> ().sharedMaterial;
tmpMaterial.globalIlluminationFlags = MaterialGlobalIlluminationFlags.BakedEmissive;
}
// Bake the lightmap.
Lightmapping.Bake ();
}
}
這里的GI屬性,我們選擇 MaterialGlobalIlluminationFlags.BakedEmissive 即可。
關(guān)于 MaterialGlobalIlluminationFlags.BakedEmissive,官方文檔說(shuō)明如下:
The emissive lighting affects baked Global Illumination. It emits lighting into baked lightmaps and baked lightprobes.
設(shè)置了GI屬性后,我們可以看到,左右2個(gè)球的材質(zhì)都出現(xiàn)在了 Light Explorer 的 Static Emissives 面板中:
并且右邊的自發(fā)光也參與了烘培:
其他
對(duì)比修改前后的材質(zhì)文件,我們發(fā)現(xiàn)主要就是 m_LightmapFlags 的設(shè)置發(fā)生了改變:
如果不想寫(xiě)代碼,我們也可以直接修改材質(zhì)文本中的 m_LightmapFlags 的設(shè)值,這里的設(shè)置和 MaterialGlobalIlluminationFlags 枚舉值是一一對(duì)應(yīng)的:
個(gè)人主頁(yè)
本文的個(gè)人主頁(yè)鏈接:https://baddogzz.github.io/2020/05/26/Emission-Bake/。
好了,拜拜!