Last active
June 28, 2025 07:09
-
-
Save maoyeedy/a8d66b314dfe671a6a9336eb4a2d15ef to your computer and use it in GitHub Desktop.
[Unity] Override Camera Ambient Color for SRP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using UnityEngine.Rendering; | |
namespace CameraAmbientOverride | |
{ | |
/// <summary> | |
/// Attach it to camera. Supports both URP and HDRP. | |
/// </summary> | |
[DisallowMultipleComponent] | |
[RequireComponent(typeof(Camera))] | |
public class CameraAmbientOverrideSrp : MonoBehaviour | |
{ | |
[SerializeField] private bool _useCustomAmbientColor; | |
[SerializeField] private Color _customAmbientColor; | |
private Camera _cam; | |
private Color _defaultAmbientColor; | |
private bool _isSubscribed; | |
private void Awake() | |
{ | |
_defaultAmbientColor = RenderSettings.ambientLight; | |
_cam = GetComponent<Camera>(); | |
} | |
private void OnEnable() | |
{ | |
SubscribeToEvents(); | |
} | |
private void OnDisable() | |
{ | |
UnsubscribeFromEvents(); | |
} | |
private void SubscribeToEvents() | |
{ | |
if (_isSubscribed) return; | |
RenderPipelineManager.beginCameraRendering += OnBeginCameraRendering; | |
RenderPipelineManager.endCameraRendering += OnEndCameraRendering; | |
_isSubscribed = true; | |
} | |
private void UnsubscribeFromEvents() | |
{ | |
if (!_isSubscribed) return; | |
RenderPipelineManager.beginCameraRendering -= OnBeginCameraRendering; | |
RenderPipelineManager.endCameraRendering -= OnEndCameraRendering; | |
_isSubscribed = false; | |
} | |
private void OnBeginCameraRendering(ScriptableRenderContext ctx, Camera cam) | |
{ | |
if (cam != _cam) return; | |
if (_useCustomAmbientColor) RenderSettings.ambientLight = _customAmbientColor; | |
} | |
private void OnEndCameraRendering(ScriptableRenderContext ctx, Camera cam) | |
{ | |
if (cam != _cam) return; | |
if (_useCustomAmbientColor) RenderSettings.ambientLight = _defaultAmbientColor; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Demo
Desktop.2025.01.23.-.23.58.03.19.mp4