Skip to content

Instantly share code, notes, and snippets.

@saguiitay
Last active October 10, 2022 13:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save saguiitay/1d9a20c5611ce5adfcf2a028fb7b51ce to your computer and use it in GitHub Desktop.
Save saguiitay/1d9a20c5611ce5adfcf2a028fb7b51ce to your computer and use it in GitHub Desktop.
Using MaterialPropertyBlock with Renderer for simple Sprite colorization
[RequireComponent(typeof(Renderer))]
public class ColorizeWithMaterialPropertyBlock : MonoBehaviour
{
void Awake()
{
var selectedColor = Color.HSVToRGB(Random.Range(0f, 1f), 1f, 1f);
var renderer = GetComponent<Renderer>();
var propBlock = new MaterialPropertyBlock();
renderer.GetPropertyBlock(propBlock);
// Assign our new value.
propBlock.SetColor("_Color", selectedColor);
// Apply the edited values to the renderer.
renderer.SetPropertyBlock(propBlock);
}
}
[RequireComponent(typeof(Renderer))]
public class CurveBasedColorsWithMaterialPropertyBlock : MonoBehaviour
{
public Color Color1, Color2;
public float Speed = 1, Offset;
public AnimationCurve Curve;
private Renderer _renderer;
private int m_colorID;
private MaterialPropertyBlock _propBlock;
void Awake()
{
_renderer = GetComponent<Renderer>();
// Get the current value of the material properties in the renderer.
_propBlock = new MaterialPropertyBlock();
_renderer.GetPropertyBlock(_propBlock);
// Get the property ID of "_Color"
m_colorID = Shader.PropertyToID("_Color");
// Setting the curve to loop
Curve.postWrapMode = WrapMode.Loop;
}
void Update()
{
// Assign our new value.
_propBlock.SetColor(m_colorID, Color.Lerp(Color1, Color2, Curve.Evaluate(Time.time * Speed)));
// Apply the edited values to the renderer.
_renderer.SetPropertyBlock(_propBlock);
}
}
[RequireComponent(typeof(Renderer))]
public class RotateColorsWithMaterialPropertyBlock : MonoBehaviour
{
public Color Color1, Color2;
public float Speed = 1, Offset;
private Renderer _renderer;
private int m_colorID;
private MaterialPropertyBlock _propBlock;
void Awake()
{
_propBlock = new MaterialPropertyBlock();
_renderer = GetComponent<Renderer>();
_renderer.GetPropertyBlock(_propBlock);
m_colorID = Shader.PropertyToID("_Color");
}
void Update()
{
// Assign our new value.
_propBlock.SetColor(m_colorID, Color.Lerp(Color1, Color2, (Mathf.Cos(Time.time * Speed + Offset) + 1) / 2f));
// Apply the edited values to the renderer.
_renderer.SetPropertyBlock(_propBlock);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment