pixelInset.set fails but new Rect is OK? (C#)

Hello all,

I have found similar but not exact answers to this problem.

I found that this produced no change to the PixelInset values:

gtWrap.pixelInset.Set(0, vec.y, 50, 50);

but this does work:

gtWrap.pixelInset = new Rect(0, vec.y, 50, 50);

Can anyone explain why this is so? I found issues with not being able to set individual pixelInset values in C# (e.g pixelInset.x) but the set method is cited as the solution.

** vec is a 2 dimensional vector and the second example proves that the values are valid*

Time to introduce you to an advanced programming topic: the difference between pass-by-value and pass-by-reference.

Rect is a struct. C# passes structs by value.

Comparing your two code samples:

gtWrap.pixelInset.Set(0, vec.y, 50, 50);

Querying gtWrap.pixelInset gets you a copy of gtWrap’s pixelInset; modifying the copy has no effect on the original.

gtWrap.pixelInset = new Rect(0, vec.y, 50, 50);

Instead of getting a value, this code sets or assigns a value. gtWrap’s pixelInset will be replaced by a copy of your value.

You can also use a temp variable:

Rect r = gtWrap.pixelInset;
r.Set(0, vec.y, 50, 50);
gtWrap.pixelInset = r;

People usually run into this trying to do something like transform.position.x = 5, which runs afoul of the same pass-by-value rules.