problem with increase alpha by code in unity5

in older version of unity with this code i was decrease and increase alpha channel for sprites by changing "myAlpha " variable.

Color tempColor = myGameObject.renderer.material.color;
tempColor.a = myAlpha;
myGameObject.renderer.material.color = tempColor;

but in unity5+ i must use “GetComponent().material.SetColor” instead of “renderer.material.color”.

and my code change like this:

Color tempColor = myGameObject.GetComponent<Renderer>().material.GetColor("_Color");
tempColor.a = myAlpha;
myGameObject.GetComponent<Renderer>().material.SetColor("_Color", tempColor);

now when i decrease “myAlpha” it works fine.
but when increase “myAlpha” nothing happens.

I’m not having issues with the second code sample you provided on a test sprite. Since you said it works when decreasing, it could be an issue with the logic that changes ‘myAlpha’. You can add a Debug.Log(myAlpha.ToString()); to check to make sure it’s actually changing the way you intended.

As for why the first code worked in older versions, it’s because Unity had a few shortcut variables (such as ‘renderer’), that did a behind the scene GetComponent. However GetComponent is actually a relatively expensive operation, so they removed them in hopes that users would instead cache the component reference.

Here’s the full code I used for testing. I created a new sprite object in a scene and applied a random sprite to it.

using UnityEngine;
using System.Collections;

public class AlphaCycle : MonoBehaviour
{
	Renderer myRenderer;

	bool fadeIn = false;
	float myAlpha = 1f;
	Color tempColor;

	void Awake()
	{
		myRenderer = GetComponent<Renderer>();
	}
	
	void Update()
	{
		if(fadeIn)
		{
			myAlpha += 0.01f;
			if(myAlpha >= 1f)
				fadeIn = !fadeIn;
		}else{
			myAlpha -= 0.01f;
			if(myAlpha <= 0f)
				fadeIn = !fadeIn;
		}

		tempColor = myRenderer.material.color;
		tempColor.a = myAlpha;
		myRenderer.material.color = tempColor;
	}
}

hi @OncaLupe
your code is working fine
but when a sprite in the scene have alpha=1 ,
but if you decrease the alpha Chanel in the editor to something like 50 from 255 ,
the top value of alpha chanel change to that.
and even with your code , you can’t set alpha to 1 (or 255) actually.
i use Unity 5.2.0f3 (32-bit)
thanks.