I have a problem with badly optimized palette cycling function of the background shader:
Shader "Background/Earthbound"
{
Properties
{
[Toggle] _Blend("Blend?", int) = 0
[Header(Texture A)]
_TexA ("Texture", 2D) = "white" {} // ensure "Repeat" wrap mode
_PaletteA("Palette Cycle", 2D) = "white" {} // ensure "Clamp" wrap mode
[Enum(None,0,Horizontal,1,Interleaved,2,Vertical,3)] _OscillationVariantA("Oscillation Variant", int) = 0
_ScrollDirXA("Scroll Direction X", float) = 1
_ScrollDirYA("Scroll Direction Y", float) = 1
_ScrollSpeedA("Scroll Speed", float) = 0
_OscillationSpeedA("Oscillation Speed", float) = 1
_OscillationAmplitudeA("Oscillation Amplitude", int) = 32
_OscillationDelayA("Oscillation Delay", int) = 1
[Header(Texture B)]
_TexB("Texture", 2D) = "white" {}
_PaletteB("Palette Cycle", 2D) = "white" {}
[Enum(None,0,Horizontal,1,Interleaved,2,Vertical,3)] _OscillationVariantB("Oscillation Variant", int) = 0
_ScrollDirXB("Scroll Direction X", float) = 1
_ScrollDirYB("Scroll Direction Y", float) = 1
_ScrollSpeedB("Scroll Speed", float) = 0
_OscillationSpeedB("Oscillation Speed", float) = 1
_OscillationAmplitudeB("Oscillation Amplitude", int) = 32
_OscillationDelayB("Oscillation Delay", int) = 1
}
SubShader
{
Tags { "RenderType"="Opaque" }
LOD 100
...
...
...
// palette cycling (too expensive right now...)
float4 paletteCycle(float4 inCol, sampler2D paletteCycle, float paletteCount)
{
float4 outCol = inCol;
int paletteIndex = -1;
for (int i = 0; i < paletteCount; i++)
{
if (inCol.a == tex2D(paletteCycle, float2(i / paletteCount, 0)).a) // match alpha values (greyscale)
{
paletteIndex = i;
}
}
if (paletteIndex >= 0)
{
int paletteOffset = (paletteIndex + _Time.y * 12) % paletteCount;
outCol = tex2D(paletteCycle, float2(paletteOffset / paletteCount, 0));
}
return outCol;
}
}
I use 2 grayscale sprites for the background animation - main bg (256x256) with "Repeat" option and palette (17x1) with "Clamp" option.
How can I optimize it?
Unity Version: 2020.