Search code examples
c#unity-game-enginerefactoringshaderunity3d-shaders

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


I'm porting a custom shader to make it work on mobile phones since shaders inside mobiles can not have if statements.

I tried 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 tried 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'


Solution

  • 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 ternary operator, you may get a headache if the logic is complex and difficult to maintain.