Search Unity

Fade object close to camera

Discussion in 'Scripting' started by skaterboy, Oct 1, 2009.

  1. skaterboy

    skaterboy

    Joined:
    Jun 6, 2009
    Posts:
    25
    Could anybody help me with a camera script that fades out object when they are close to the camera.

    If the object is close/in front of the camera the opacity is set to 50% .......

    Any hints/help ???????
     
  2. cj-currie

    cj-currie

    Joined:
    Nov 27, 2008
    Posts:
    337
    Use GameObject.renderer.material.color.a to control the alpha of an object.
     
  3. skaterboy

    skaterboy

    Joined:
    Jun 6, 2009
    Posts:
    25
    ok, Nice it worked out after a bit of truble ....
    I realized that I had to use the transparent shader (But I want to use the Toon shader)

    How could I make a Toon shaded object transparent ?

    I used this script
    Code (csharp):
    1. if (Camera.main.WorldToViewportPoint(transform.position).z < 5)
    2.         renderer.material.color.a = 0.5;
     
  4. cj-currie

    cj-currie

    Joined:
    Nov 27, 2008
    Posts:
    337
    Instead of
    Code (csharp):
    1. if (Camera.main.WorldToViewportPoint(transform.position).z < 5)
    use

    Code (csharp):
    1. (Camera.main.transform.position - transform.position).magnitude
    It tells you how far away something is.

    Toon shaders are just like diffuse shaders, and also can use renderer.material.color.a.
     
  5. skaterboy

    skaterboy

    Joined:
    Jun 6, 2009
    Posts:
    25
    ok, thanks.

    But the
    Code (csharp):
    1. renderer.material.color.a
    didn't work with toon shaders ( I have to use the transparent shaders )
     
  6. cj-currie

    cj-currie

    Joined:
    Nov 27, 2008
    Posts:
    337
    Hmm...I dont' actually know if there exists a transparent toon shader.
     
  7. hai_ok

    hai_ok

    Joined:
    Jun 20, 2007
    Posts:
    193
    I did not write this. So I give credit to the person who did.
     

    Attached Files:

  8. Barbaric

    Barbaric

    Joined:
    Jan 20, 2013
    Posts:
    1
    That script seems like just what I need, but I get an error on line 125 stating that there is already a local variable with the name ‘newMaterial’.
     
  9. JessyDL

    JessyDL

    Joined:
    Nov 27, 2012
    Posts:
    60
    Why not do this in a shader? Arguably a lot more optimized and the standard way of doing this.
    Seeing the camera is already being parsed to the shader, and ofcourse the vertex positions, it's should be no issue to calculate the distance and go from there.