renderer.material.color.a

I’m having a problem with this:

  void Update(){

	var staticObject = GameObject.Find("staticObject");

	if(staticObject)
		{

			staticRenderer = staticObject.renderer;

			staticRenderer.material.color.a = 0.0f;
		}
		else
		{
			Debug.LogWarning("Not found");
		}
	}

It gives me:

Cannot modify a value type return value of `UnityEngine.Material.color'. Consider storing the value in a temporary variable

How can i fix this?

I'm not sure where the problem is, I just ran it and it works. Is that definitely the code that's causing the problem?

3 Answers

3

staticRenderer.material.color is a property, that means it is basically a function and it returns a Color struct. Because Color is a struct, and not a class, you get a copy. Changing the copy does absolutely nothing to the original.

If it were a class, you would get a reference and you could modify it like that you are trying.

The common form for what you are trying to do is:

  1. Retrieve the original.
  2. Modify it.
  3. Store it back to where it was.

Here it is in code:

Color color = staticRenderer.material.color;
color.a = 0.0f;
staticRenderer.material.color = color;

It is sometimes a good idea to create helper functions to make it easier.

function changeAlpha(var color, var newAlpha)
{
  color.a = 0.0f;
  return color;
}

Then you could use it like this:

staticRenderer.material.color = changeAlpha(staticRenderer.material.color, 0.0f);

Helped a lot, thanks bud!

will this same solution work with "renderer.material.color.r" ?

very good explanation. even newb like me could understand thanks

In C# you need to write it like this:

staticRenderer.material.color = new Color(1.0f, 1.0f, 1.0f, 0.0f);

This will set everything, not just the alpha.

The other answers are better to just switch the alpha

The alpha channel in the color component is readonly and cannot be assigned. So if you only want to change the alpha value, you’ll need to store the color in a temp variable as the error suggests, then change the temp and reassign the color value.

var color = staticRenderer.material.color;
color.a = 0.0f;
staticRenderer .material.color = color;