TMPEffects
TMPEffects copied to clipboard
PaletteAnimation throws IndexOutOfRangeException at wave crests or troughs
Describe the bug
PaletteAnimation can throw an IndexOutOfRangeException when the calculated color index equals the length of the colors array. This occurs at wave crests or troughs where the wave amplitude produces an index that is out of bounds.
To Reproduce
- Create a
PaletteAnimationwith multiple colors assigned. - Use a wave that reaches its maximum amplitude.
- Play the animation until the wave hits its crest or trough.
- Observe the exception thrown in the console.
Expected behavior
The animation should safely handle the color index, looping or clamping it to remain within the array bounds, without throwing exceptions.
Additional context
The bug is caused by this code:
float index = Mathf.Abs((d.colors.Length) * (d.wave.Amplitude == 0 ? 0 : result.Item1 / d.wave.Amplitude));
int intIndex = (int)index;
d.colors[intIndex]; // Can throw IndexOutOfRangeException
A safe fix is to clamp the index:
int intIndex = Mathf.Clamp((int)index, 0, d.colors.Length - 1);
or use modulo to loop the colors:
int intIndex = ((int)index) % d.colors.Length;