Skip to content

Instantly share code, notes, and snippets.

@jackbrookes
Last active April 27, 2019 16:06
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 jackbrookes/1dd6cc63e015f4eb328faa037a6804d6 to your computer and use it in GitHub Desktop.
Save jackbrookes/1dd6cc63e015f4eb328faa037a6804d6 to your computer and use it in GitHub Desktop.
Extensions for the Unity Texture2D class allowing add/subtract/multiply operations on other textures as well as singe colours.
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public static class Texture2DExtensions
{
public static void Add(this Texture2D tex1, Texture2D tex2)
{
if (tex1.width != tex2.width) throw new ArgumentException("Textures must have the same width!");
if (tex1.height != tex2.height) throw new ArgumentException("Textures must have the same height!");
for (int i = 0; i < tex1.width; i++)
for (int j = 0; j < tex1.height; j++)
tex1.SetPixel(i, j, tex1.GetPixel(i, j) + tex2.GetPixel(i, j));
}
public static void Subtract(this Texture2D tex1, Texture2D tex2)
{
if (tex1.width != tex2.width) throw new ArgumentException("Textures must have the same width!");
if (tex1.height != tex2.height) throw new ArgumentException("Textures must have the same height!");
for (int i = 0; i < tex1.width; i++)
for (int j = 0; j < tex1.height; j++)
tex1.SetPixel(i, j, tex1.GetPixel(i, j) - tex2.GetPixel(i, j));
}
public static void Multiply(this Texture2D tex1, Texture2D tex2)
{
if (tex1.width != tex2.width) throw new ArgumentException("Textures must have the same width!");
if (tex1.height != tex2.height) throw new ArgumentException("Textures must have the same height!");
for (int i = 0; i < tex1.width; i++)
for (int j = 0; j < tex1.height; j++)
tex1.SetPixel(i, j, tex1.GetPixel(i, j) * tex2.GetPixel(i, j));
}
public static void Add(this Texture2D tex1, Color color)
{
for (int i = 0; i < tex1.width; i++)
for (int j = 0; j < tex1.height; j++)
tex1.SetPixel(i, j, tex1.GetPixel(i, j) + color);
}
public static void Subtract(this Texture2D tex1, Color color)
{
for (int i = 0; i < tex1.width; i++)
for (int j = 0; j < tex1.height; j++)
tex1.SetPixel(i, j, tex1.GetPixel(i, j) - color);
}
public static void Multiply(this Texture2D tex1, Color color)
{
for (int i = 0; i < tex1.width; i++)
for (int j = 0; j < tex1.height; j++)
tex1.SetPixel(i, j, tex1.GetPixel(i, j) * color);
}
public static Texture2D Copy(this Texture2D tex1)
{
Texture2D tex2 = new Texture2D(tex1.width, tex1.height);
tex2.SetPixels(tex1.GetPixels());
return tex2;
}
public static void Replace(this Texture2D tex1, Color color)
{
for (int i = 0; i < tex1.width; i++)
for (int j = 0; j < tex1.height; j++)
tex1.SetPixel(i, j, color);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment