Change Material's Alpha

Hello,

I am trying to change a material’s alpha on a game object via code. I want the alpha to fade in and out base on distance. I am using Unity 5, and I don’t think this code works anymore.

  alphaValue = Mathf.Lerp(renderer.material.color.a, 0F,
        Time.deltaTime * fadeLerpConstant); 

Any suggestions on how to achieve this?

Thanks,

John L

Hi, i am currently testing this and trying out things too.
First of all alpha on materials set to opacity wont work, you have to set it transparent.
Setting materials to transparent by default from optimization perspective would not be a good option. So to change that via code:

MeshRenderer renderer = gameObject.GetComponent<MeshRenderer>();
Material material = renderer.material;

material.SetFloat("_Mode", 4f);

//0f - opacity
//1f - cutout
//2f - fade
//3f - transparent

But this wont work out of the box (i wish it would).
In one of the unity forum posts i saw that you have to set rest of the properties.

material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha);
material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
material.SetInt("_ZWrite", 0);
material.DisableKeyword("_ALPHATEST_ON");
material.EnableKeyword("_ALPHABLEND_ON");
material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
material.renderQueue = 3000;

I am not shader expert, so if someone could elaborate what exactly these do and are of them even needed i would be thankful.

What comes to color itself, i got it working this way.
I set these before rest of the properties, right after switching the mode.

Color32 col = renderer.material.GetColor("_Color");
col.a = 100;
renderer.material.SetColor("_Color", col);