using UnityEngine;
/// <summary>
/// Simple per-renderer material block that can be altered from multiple sources.
/// </summary>
public class CustomMaterialBlock : MonoBehaviour
{
Renderer mRen;
MaterialPropertyBlock mBlock;
public OnWillRenderCallback onWillRender;
public delegate void OnWillRenderCallback (MaterialPropertyBlock block);
void Awake ()
{
mRen = GetComponent<Renderer>();
if (mRen == null) enabled = false;
else mBlock
= new MaterialPropertyBlock
(); }
void OnWillRenderObject ()
{
if (mBlock != null)
{
mBlock.Clear();
if (onWillRender != null) onWillRender(mBlock);
mRen.SetPropertyBlock(mBlock);
}
}
}
/// <summary>
/// Allows for renderer.AddOnRender convenience functionality.
/// </summary>
static public class CustomMaterialBlockExtensions
{
static public CustomMaterialBlock AddOnRender (this Renderer ren, CustomMaterialBlock.OnWillRenderCallback callback)
{
UnityEngine.Profiling.Profiler.BeginSample("Add OnRender");
var mb = ren.GetComponent<CustomMaterialBlock>();
if (mb == null) mb = ren.gameObject.AddComponent<CustomMaterialBlock>();
mb.onWillRender += callback;
UnityEngine.Profiling.Profiler.EndSample();
return mb;
}
static public void RemoveOnRender (this Renderer ren, CustomMaterialBlock.OnWillRenderCallback callback)
{
UnityEngine.Profiling.Profiler.BeginSample("Remove OnRender");
var mb = ren.GetComponent<CustomMaterialBlock>();
if (mb != null) mb.onWillRender -= callback;
UnityEngine.Profiling.Profiler.EndSample();
}
}