0
\$\begingroup\$

I have a canvas. It has an empty game object as a child. That object has a RectTransform component. The RectTransform pivot value is set to 0.4, 0.5 (x, y). In some code I wanted to update the pivot value using the following:

Debug.Log(((RectTransform)transform).pivot);  // logs: (0.4, 0.5)
((RectTransform)transform).pivot.Set(0.3f, 0.8f);
Debug.Log(((RectTransform)transform).pivot);  // logs: (0.4, 0.5)

I don't know why the set command is not working. The tooltip for Set is: "Set x and y components of an existing Vector2"

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

You need to use:

((RectTransform)transform).pivot = new Vector2(0.3f, 0.8f);

The tool tip for .Set is correct that it mutates the Vector2. But the .pivot is a getter and because Vector2 is a struct it means .pivot returns a copy of the Vector2, not a reference.

If you wanted to use .Set then you'd need to use:

var new_pivot = ((RectTransform)transform).pivot.Set(0.3f, 0.8f);
((RectTransform)transform).pivot = new_pivot;
\$\endgroup\$
5
  • 1
    \$\begingroup\$ .Set is indeed a mutation. It mutates the Vector2 instance you call it on. .pivot is a getter. It gives you a copy of the Vector2 used as a pivot. So your original code says "Take a copy of the pivot, set the copy to a new value, then discard the copy without ever modifying the original" — what you really want to do is assign to the original pivot, which is what the = operator does for you in your updated code. \$\endgroup\$
    – DMGregory
    Nov 14, 2019 at 16:18
  • \$\begingroup\$ So the .pivot gives a copy not a reference. Thank you. \$\endgroup\$
    – AJP
    Nov 14, 2019 at 16:49
  • 1
    \$\begingroup\$ This is the case in general for struct types in C#, which are value types rather than reference types. \$\endgroup\$
    – DMGregory
    Nov 14, 2019 at 16:51
  • \$\begingroup\$ Seriously look into the differences of structs and classes. It's quite important to know about them when working with C#. You might also want to create structs at some point. The main things to distinguish are mutable (normal classes) & immutable (strings) reference types and structs (int, TimeSpan, double). \$\endgroup\$
    – Battle
    Jan 15, 2020 at 14:10
  • 1
    \$\begingroup\$ Thanks @Battle yeah I've tried a view times with stuff like "When should I use a struct or class", "struct vs class", "difference between" etc. But from these resources I didn't appreciate the significance of "reference semantics"... I do now! :) docs.microsoft.com/en-us/dotnet/csharp/programming-guide/… stackoverflow.com/questions/521298/when-to-use-struct \$\endgroup\$
    – AJP
    Jan 15, 2020 at 15:09

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .