Domanda

I want to change the alpha value of an existing color. However, I cannot directly edit the color.

When I try something like this:

gui.color.a = 0;

I get the following error:

Error: Cannot modify the return value of 'UnityEngine.GUITexture.color' because it is not a variable.

But if I copy the variable I am able to edit the alpha value.

Color tempColor = gui.color;
tempColor .a = .25f;
gui.color = tmpclr;

Why is this? Why is the new instance of the Color not throwing the same error?

Additionally, I thought that because I had to do this often I would write a little extension method like this:

private static Color tempColor;
public static void SetAlpha(this Color color, float alpha)
{
    tempColor = color;
    tempColor.a = alpha;
    color = tempColor;
}

But to my surprise this compiled but didn't change the alpha value at all. Can anyone explain why this might not be working?

È stato utile?

Soluzione

In C#, structs are passed by value.

When you get gui.color, you're getting a copy of the GUITexture's color; changes made to the copy do not alter the original.

The following doesn't work, because you're modifying and discarding a copy:

gui.color.a = 0;

The following does work, because you're getting a copy, modifying it, and passing it back:

Color tempColor = gui.color;
tempColor.a = .25f;
gui.color = tmpclr;

An extension method for Color fails for the same reason: the extension method will be called on the copy, not the original. You could write an extension method for GUITexture, instead:

public static void SetAlpha(this GUITexture self, float alpha) {
    Color tempColor = self.color;
    tempColor.a = alpha;
    self.color = tempColor;
}

Altri suggerimenti

You're getting the error message, because by using c# as scripting language your are getting a struct as the color attribute. This means you are getting a copy of the color variable:

gui.color // this is a struct and also a copy of the original color attribute

So the compiler warns you about making an unnecessary change to a copy.

Have a look at this question: Cannot modify the return value error c#

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top