The example camera.backgroundColor.r = 1
from the comment simply won't work. You will get the following error
Cannot modify the return value of 'Camera.backgroundColor' because it is not a variable
and the reason has been discussed here. The point is that in Unity
the Camera
itself is the class
but the Color
(the type of the backgoundColor
) is mutable struct
, be careful though they are evil.
When you assign a new value to a variable of a value type, that value
is copied. When you assign a new value to a variable of a reference
type, the reference is copied, not the object itself
public class Camera
{
public BackgroundColorValue backgroundColorValue { get; set; }
= new BackgroundColorValue();
public BackgroundColorRef backgroundColorRef { get; set; }
= new BackgroundColorRef();
}
public struct BackgroundColorValue
{
public int r { get; set; }
public int g { get; set; }
public int b { get; set; }
}
public class BackgroundColorRef
{
public int r { get; set; }
public int g { get; set; }
public int b { get; set; }
}
var shortCutValue = cammera.backgroundColorValue;
var shortCutRef = cammera.backgroundColorRef;
shortCutValue.r = 5;
shortCutRef.r = 10;
//cammera.backgroundColorValue.r == 0, shortCutValue == 5
//cammera.backgroundColorRef.r == 10, shortCutValue == 10
The value
types are copied by value so shortCutValue
doesn't have any connection with the camera.backgroundColor.r
except they have the same value in one period of their existance. On the other hand, shortCutRef
is an actual shortcut and it will work until you change the reference to the backgroundColorRef
which might be possible if Camera
is mutable.
var shortCutRef = cammera.backgroundColorRef;
camera.backgroundColorRef = new BackgroundColorRef(); //link to shortcut broken
shortCutRef.r = 10;
//cammera.backgroundColorRef.r == 0, shortCutValue == 10
I am not sure if this is applicable in general, there might be some case Eric knows, but if you have A.B.C.D....N.r
you could make a shortcut if N
is actually reference
type and to be sure the link with the shortcut will be unbreakable all types from N to A should be immutable. Otherwise, you could break a link somewhere.