Home > Mobile >  How do I replace if statements with ? operator for making a shader work on mobile?
How do I replace if statements with ? operator for making a shader work on mobile?

Time:02-08

I'm porting a custom shader to make it work on mobile phones since shaders inside mobiles can not have if statements. I tryed replacing the if statements of my code with the ? operator but I can not compile in Unity without errors. I'm pretty new to c# so it is obvious to myself I am missing something here to complete this. Any advice from more experienced programmers here? Many thanks to you all.

// The original code is commented.

I also tryed to store the result inside a variable and return it but also didn't work.

/*  if (charCol.r > .8f) {
                    if(_monochromatic == 1)
                        return float4(0, gray, 0, 1);
                    else
                        return col;
                }
                else {
                    return col * _brightness;
                }   */
                charCol.r > .8f ? (_monochromatic == 1) ? return float4(0, gray, 0, 1) : return col : return col * _brightness;

Error message: Shader error in 'Custom/Shader': syntax error: unexpected token 'return'

CodePudding user response:

You should return as below:

return charCol.r > .8f 
    ? ((_monochromatic == 1) ? float4(0, gray, 0, 1) : col) 
    : col * _brightness;

Small opinion:

Even you can return value with the null coalescing operator, you may get a headache if the logic is complex and difficult to maintain.

  •  Tags:  
  • Related