Search Unity

Question Strange shader color behavior

Discussion in 'General Graphics' started by unity_6255F9AC6E8A43BB555E, May 10, 2023.

  1. unity_6255F9AC6E8A43BB555E

    unity_6255F9AC6E8A43BB555E

    Joined:
    Apr 12, 2023
    Posts:
    2
    I have a sprite renderer with a star image (representing the point light of a planet) that is supposed to fade out when the camera gets to close to it. All it does is adjusts the shader's _Color alpha (the actual color used is set by _Emissive).

    It works fine when adjusting it from the inspector without the script,

    Alpha 1.0
    Capture.PNG

    Alpha 0.0
    Capture2.PNG


    but when I adjust it from this script:

    Code (CSharp):
    1. void Update()
    2.     {
    3.         float distance          = (_cam.transform.position - transform.position).magnitude;
    4.         float alpha             = (distance - _fadeEndDistance) / _range;
    5.  
    6.         Color color             = new Color(0, 0, 0, alpha);
    7.         _spriteRenderer.material.SetColor("_Color", color);
    8.     }
    all of the sudden it leaves this semi-transparent sprite that doesn't go away unless I also adjust _Emissive to black from the inspector.

    Capture3.PNG
    You can sort of see the red tinted stars (the emissive color is blue-teal) when it should be completely transparent like the second image. The _Color alpha shows as 0.0 in the inspector, as expected.

    Now I could just adjust _Emissive by script as well, but it makes absolutely no sense. It works perfectly when I manually adjust it, but adding just the code that does exactly the same thing causes different results?

    I'll include the shader since it's custom for the bloom effect. Probably not the best way to do it but it was the only way I could (sort of) getting it working properly:

    Capture4.PNG

    If anyone has any idea of what could be causing this I would greatly appreciate it.
     
  2. unity_6255F9AC6E8A43BB555E

    unity_6255F9AC6E8A43BB555E

    Joined:
    Apr 12, 2023
    Posts:
    2
    I'm a donkey. I just had to clamp the alpha like so:

    alpha  = Mathf.Clamp( (distance - _fadeEndDistance) / _range, 0f, 1f);

    Wasted a good chunk of the evening messing with shaders, etc... and then I realized it obviously has to be from those 4 lines of code and fixed it 3 minutes after posting.