make a gameobject lerp transparency?

I’m trying to make my player gameobject flash/blink transparency (over 1 second, go from alpha 1.0 to 0.1 and back up to 1.0)

Firstly, I know to make an object transparent, you have to (and I have done):

  1. change the object’s material from diffuse to transparent → diffuse

  2. use the code:

    Color tempcolor = gameobject.renderer.material.color
    tempcolor.a = (float between 0.0 and 1.0); //0 is invis, 1 is fully visible
    gameobject.renderer.material.color = tempcolor;

I then put this in a While loop (while my player’s gameobject has not moved) and added in code to increase/decrease the float accordingly each time this was called. However when I try to playtest the game, Unity freezes/crashes. I’m not sure what’s wrong with it so I’m not sure what to fix :confused:

Would it be better to make this a coroutine? Use mathf.lerp? What should I do? (NOTE: While it’s flashing, it should still be able to read the rest of the code in my update function. Hitting wasd is what ends the flashing)

Thanks for any help :slight_smile:

EDIT: So this is my current code: private float transparency = 1f;private bool transparencyGoingUp = false;pri - Pastebin.com – hopefully it should be quick/easy to understand!

My problem is that no matter what I set waitTime to, it still updates the alpha every frame rather than waiting after it updates. I want an entire cycle to take 0.75sec but currently it’s entirely dependent on FPS and happens way too quickly

Don’t use a while loop.
Use Mathf.MoveTowards, which changes a value over time to a target value…

Color tempcolor = gameobject.renderer.material.color
tempcolor.a = Mathf.MoveTowards(0, 1, Time.deltaTime);
gameobject.renderer.material.color = tempcolor;

So… This is my current code: private float transparency = 1f;private bool transparencyGoingUp = false;pri - Pastebin.com – hopefully it’s very quick/easy to understand :slight_smile:

My only problem is no matter what I set my timer variable (waitTime), the flashing happens incredibly quickly, as if the alpha is being incremented/decremented every frame. How do I space it out over a certain amount of time (roughly 0.75sec)?