Here’s some code I just wrote up to do this:
*Be sure to read the comments defining the difference between Compare()
and QuickCompare()
. Compare()
is moderately costly, so I suggest you use that only if you plan on using it as an editor extension or for in-editor testing purposes.
GradientMagic.cs
using UnityEngine;
public static class GradientMagic {
public static bool Compare(this Gradient gradient, Gradient otherGradient) {
// Compare the lengths before checking actual colors and alpha components
if (gradient.colorKeys.Length != otherGradient.colorKeys.Length || gradient.alphaKeys.Length != otherGradient.alphaKeys.Length) {
return false;
}
// Compare all the colors
for (int i = 0; i < gradient.colorKeys.Length; i++) {
// Test if the color and alpha is the same
GradientColorKey key = gradient.colorKeys*;*
_ GradientColorKey otherKey = otherGradient.colorKeys*;_
_ if (key.color != otherKey.color || key.time != otherKey.time) {_
_ return false;_
_ }_
_ }*_
* // Compare all the alphas*
* for (int i = 0; i < gradient.alphaKeys.Length; i++) {*
* // Test if the color and alpha is the same*
_ GradientAlphaKey key = gradient.alphaKeys*;
GradientAlphaKey otherKey = otherGradient.alphaKeys;
if (key.alpha != otherKey.alpha || key.time != otherKey.time) {
return false;
}
}*_
* // They’re the same*
* return true;*
* }*
* /// Compares the two gradients by testing points at a given interval, note this does not detect when new nodes are added*
* public static bool QuickCompare(this Gradient gradient, Gradient otherGradient, int testInterval = 3) {*
* // Tests the gradient at a couple points to see if they are the same, may fail is various cases*
* for (int i = 0; i < testInterval; i++) {*
* float time = (float) i / (float) (testInterval - 1);*
* if (gradient.Evaluate(time) != otherGradient.Evaluate(time)) {*
* return false;*
* }*
* }*
* // All the test points match*
* return true;*
* }*
}
### GradientChangeTester.cs
using UnityEngine;
[ExecuteInEditMode]
public class GradientChangeTester : MonoBehaviour {
* /// The first gradient*
* public Gradient gradient = new Gradient();*
* /// The second gradient*
* private Gradient oldGradient = new Gradient();*
* /// Determines wether or not to use the QuickCompare method*
* public bool useQuickCompare;*
* /// The number of testing points for a quick compare*
* public int quickCompareTestInterval = 5;*
* public void Update() {*
* if (useQuickCompare) {*
* if (oldGradient == null || !gradient.QuickCompare(oldGradient, quickCompareTestInterval)) {*
* PrintChanged();*
* oldGradient.SetKeys(gradient.colorKeys, gradient.alphaKeys);*
* }*
* } else {*
* if (oldGradient == null || !gradient.Compare(oldGradient)) {*
* PrintChanged();*
* oldGradient.SetKeys(gradient.colorKeys, gradient.alphaKeys);*
* }*
* }*
* }*
* /// Used for debugging purposes to print when a gradient is changed*
* public void PrintChanged() {*
* print(“Gradient changed.”);*
* }*
}