使用OnPreRender(),OnPostRender(),Unity渲染仅阴影1个主摄像机

时间:2019-06-05 07:09:04

标签: c# unity3d camera shadow

我有4台相机。 1个主摄像机和3个子摄像机。

我不想在3个子摄像机中渲染阴影,所以我将下面的代码附加到3个子摄像机上。

// https://answers.unity.com/questions/1219726/make-shadows-disappear.html

private void OnPreRender()
{
    shadowDisatance = QualitySettings.shadowDistance;
    QualitySettings.shadowDistance = 0;
}

private void OnPostRender()
{
    QualitySettings.shadowDistance = shadowDisatance;
}

它工作正常,但我只是不想将此脚本附加到3个子摄像机。相反,我只想制作一个脚本并将其仅附加到1个主摄像机。

当然,下面的代码的目的是使主摄影机仅渲染阴影。

private void OnPreRender()
{
    QualitySettings.shadowDistance = 40;
}

private void OnPostRender()
{
    QualitySettings.shadowDistance = 0;
}

但这会使主摄像机不渲染阴影。它只是使每个shadowDistance为0。

请帮助。

1 个答案:

答案 0 :(得分:1)

我真的不明白为什么,但是如果您不想在子摄像机上附加任何东西,可以改而使用Camera.onPreRenderCamera.onPostRender并让它对除mainCamera之外的所有摄像机执行此操作。

正如我所说,我宁愿更改QualitySettings.shadows而不是shadowDistance,但这显然取决于您。

类似这样的东西

[RequireComponent(typeof(Camera))]
public class DisableSubCamShadows : MonoBehaviour
{
    // either drag this in via the inspector
    public Camera mainCamera;

    private ShadowQuality _originalShadowSettings

    // or get it on runtime
    private void Awake()
    {
        // mainCamera will be the one attached to this object
        mainCamera = GetComponent<Camera>();

        // store original shadow settings
        _originalShadowSettings = QualitySettings.shadows;
    }

    private void OnEnable()
    {
        // register the callbacks when enabling object
        Camera.onPreRender += MyPreRender;
        Camera.onPostRender += MyPostRender;
    }

    private void OnDisable()
    {
        // remove the callbacks when disabling object
        Camera.onPreRender -= MyPreRender;
        Camera.onPostRender -= MyPostRender;
    }

    // callback before ANY camera starts rendering
    private void MyPreRender(Camera cam)
    {
        // if mainCamera set to originalShadowSettings 
        // could also simply return but just to be sure
        //
        // for other camera disable shadows
        QualitySettings.shadows = cam == mainCamera ? originalShadowSettings : ShadowQuality.Disable;   
    }

    // callback after ANY camera finishes rendering
    private void MyPostRenderer(Camera cam)
    {
        // restore shadow settings
        QualitySettings.shadows = originalShadowSettings;
    }
}

将此附加到MainCamera