- Home /
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?
Answer by Subhajit-Nath · Nov 27, 2013 at 05:30 PM
In C# you need to write it like this:
staticRenderer.material.color = new Color(1.0f, 1.0f, 1.0f, 0.0f);
Answer by Spinnernicholas · Nov 27, 2013 at 06:05 PM
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:
Retrieve the original.
Modify it.
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);
will this same solution work with "renderer.material.color.r" ?
very good explanation. even newb like me could understand thanks
Answer by Key_Less · Nov 27, 2013 at 06:02 PM
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;