Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question Strange shader color behavior

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

  1. unity_6255F9AC6E8A43BB555E


    Apr 12, 2023
    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

    Alpha 0.0

    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;
    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.

    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:


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


    Apr 12, 2023
    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.