Search Unity

Fade out a gameobject

Discussion in 'Scripting' started by herbie, Jun 18, 2013.

  1. herbie

    herbie

    Joined:
    Feb 11, 2012
    Posts:
    237
    I let a gameobject fade out like this:

    Code (csharp):
    1. for (t = 0.0; t < 1.0; t += Time.deltaTime)
    2.             {
    3.                 Object.renderer.material.color.a = Mathf.Lerp(1, 0, t)
    4.             }
    But when it is done, it is still a little bit visible (on my galaxy note). You still can see the contours a little.
    I think it has something to do with timing but I'm not sure.
    Can anybody tell me how to let it fade out complete?
     
  2. Patico

    Patico

    Joined:
    May 21, 2013
    Posts:
    886
    I can suggest workaround - disable mesh renderer, to guarantee visibility of object:

    Code (csharp):
    1. Object.renderer.enabled = false;
    or:
    Code (csharp):
    1. Object.renderer.enabled = Object.renderer.material.color.a > 0.01F;
     
  3. stanislav-osipov

    stanislav-osipov

    Joined:
    May 30, 2012
    Posts:
    1,790
    Here you go

    Code (csharp):
    1. iTween.FadeTo(gameObject, iTween.Hash("alpha", 0f,  "time", time));
     
  4. Patico

    Patico

    Joined:
    May 21, 2013
    Posts:
    886
    The reason of you issue is here "t += Time.deltaTime" - you increnent t variable by deltaTime value.
    So if t = 0.95 and deltaTime = 0.5, then next value of t will equals 1.45 and for cycle will not run - last value of t will be 0.95 - and object still a little bit visible.

    Alternate way is allow t to be greater then 1:
    Code (csharp):
    1.    
    2. for (t = 0.0; t < 2.0; t += Time.deltaTime)
    3. {
    4.      Object.renderer.material.color.a = Mathf.Lerp(1, 0, t)
    5. }
     
  5. herbie

    herbie

    Joined:
    Feb 11, 2012
    Posts:
    237
    Thank you all for your quick reply.

    t greater than 1 was the solution. And I understand why, thanks Patico.