Skip to content

Instantly share code, notes, and snippets.

@behreajj
Last active November 10, 2021 03:41
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 behreajj/e89bf3d1d9308219cdff5e2dcde240ec to your computer and use it in GitHub Desktop.
Save behreajj/e89bf3d1d9308219cdff5e2dcde240ec to your computer and use it in GitHub Desktop.
Unity Grayscale Setup
using UnityEngine;
[RequireComponent (typeof (SpriteRenderer))]
public class Grayscale : MonoBehaviour
{
void Start ( )
{
SpriteRenderer renderer = GetComponent<SpriteRenderer> ( );
Sprite sprite = renderer.sprite;
Texture2D srcTexture = sprite.texture;
int width = srcTexture.width;
int height = srcTexture.height;
Color[ ] srcPixels = srcTexture.GetPixels (0, 0, width, height);
int len = srcPixels.Length;
Texture2D trgTexture = new Texture2D (width, height);
Color[ ] trgPixels = new Color[len];
for (int i = 0; i < len; ++i)
{
int x = i % width;
int y = i / width;
Color srcPixel = srcPixels[i];
float gray = GrayMethod (srcPixel);
trgPixels[i] = new Color (
gray, gray, gray,
srcPixel.a);
}
trgTexture.SetPixels (trgPixels);
trgTexture.Apply ( );
renderer.sprite = Sprite.Create (
trgTexture,
new Rect (0, 0, width, height),
new Vector2 (0.5f, 0.5f));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment