How to change guitext alpha value without error cs1612?

I get this error while trying to change the alpha value of a guitext:
“Assets/FloatingText.cs(47,34): error CS1612: Cannot modify a value type return value of `UnityEngine.Material.color’. Consider storing the value in a temporary variable”

I did a ton of googling around, and no matter how I try to adapt the things I found I just can’t get it working. The example script this is based on is unfortunately in Javascript, which apparently handles the thing that causes this error a bit different.

public class FloatingText : MonoBehaviour {
	    	     		
	
	private float speed = 0.03f;
	private float alpha;
	public float guiTime = 5f;
	private float duration = 1.5f;

	void Start()
	{
		guiText.material.color = Color.red;
		alpha = 1f;
		StartCoroutine(GuiDisplayTimer());
	}
	
	void Update()
	{
		//Debug.Log(guiText.material.color.a);
		transform.Translate(new Vector3(0f, 2f, 0f) * (speed * Time.deltaTime));
		//alpha = guiText.material.color.a; //Tried setting alpha into a temp variable but ain't working
		alpha -= Time.deltaTime/duration; 
		guiText.material.color.a = alpha;

	} 
	
	IEnumerator GuiDisplayTimer()
    {
        yield return new WaitForSeconds(guiTime);

        Destroy(this.gameObject);
    }
	

    
}

It must be a very simple thing to do, but every place that advices how to get around this error does it in a way that just seems totally incomprehensible. I have tried so many things with this it’s really frustrating right now. Here’s the script I have based this on : attack damage scrolling - Unity Answers

Thanks in advance.

Do we know what optimization happens? Maybe all the guff disappears, and so it's just coded like that for simplicity.

Then im sorry, i dont have an other idea. What could work, try adding a layer by adding public LayerMask DedectableLayers; and putting them into the parameters of Physics.OverlapSphere();

1 Answer

1

As the error says, assign the the whole Color, not one component.

var c = .....color;
c.a = alpha;
.....color = c;

Or use JavaScript which handles these things for you.

Certainly the docs could male it clearer when values are value types (like Color and Vector3), and when they are referenced objects (like Material and Transform).

I deliberately answered generically, so as long as your working code follows that pseudocode, it's not necessary to post it. The idea is that Questions, once answered, have the broadest applicability.

I still don't quite understand, could you please explain how one would put this pseudo code in C#?