Skip to content

Instantly share code, notes, and snippets.

@yagero
Created November 21, 2017 13:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yagero/d4b377a4fa318b01f6b6e9c5a533141b to your computer and use it in GitHub Desktop.
Save yagero/d4b377a4fa318b01f6b6e9c5a533141b to your computer and use it in GitHub Desktop.
Use this class (instead of a PostProcessingBehaviour) to dynamically instantiate the PostProcessingProfile at runtime: this allows you to modify the properties of the profile during playtime, without modifying the profile asset
using UnityEngine;
using UnityEngine.PostProcessing;
using System.Collections.Generic;
/// <summary>
/// Use this component to dynamically create a PostProcessingBehaviour and instantiate a PostProcessingProfile on a Camera
/// This allows you to dynamically modify at runtime the PostProcessingProfile, without modifying the asset.
/// This component keeps track of the Profile and Instances. This means that if 2 different camera use the same Profile, they will use the same Instance.
/// </summary>
[RequireComponent(typeof(Camera))]
public class InstantiatePostProcessingProfile : MonoBehaviour
{
[SerializeField] PostProcessingProfile m_Profile = null;
static Dictionary<PostProcessingProfile, PostProcessingProfile> ms_RefToInstance = new Dictionary<PostProcessingProfile, PostProcessingProfile>();
static PostProcessingProfile AssignProfile(PostProcessingProfile reference)
{
if (!reference)
return null;
// keep track of the profile and instances: only 1 instance is created per profile
// (event if multiple cameras share 1 profile)
if (!ms_RefToInstance.ContainsKey(reference))
{
var profileInstance = Object.Instantiate(reference);
QualitySettingsAdjustments(profileInstance);
ms_RefToInstance.Add(reference, profileInstance);
}
return ms_RefToInstance[reference];
}
T GetOrAddComponent<T>() where T : Component
{
var component = gameObject.GetComponent<T>();
if (component == null)
component = gameObject.AddComponent<T>();
return component;
}
void Start()
{
if (m_Profile)
{
var ppb = GetOrAddComponent<PostProcessingBehaviour>();
Debug.Assert(ppb);
ppb.profile = AssignProfile(m_Profile);
}
Object.Destroy(this);
}
static void QualitySettingsAdjustments(PostProcessingProfile profile)
{
// Here you can adjust the PostProcessingProfile just after instantiation.
// For example you can change it according to the Quality Settings.
// Like here we disable Motion Blur for low quality.
if (QualitySettings.GetQualityLevel() < 1)
profile.motionBlur.enabled = false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment