[SOLVED] Getting properties from "transform": clones or references ?

Hi !

I was looking for a way to programatically reset a gameObject’s initial rotation and I ran into this thread:

In it, the replier (named “aldonaletto”) declares a class property called “originalRotationValue” (of type Quaternion) and initializes it inside the “Start” method with the current gameObject’s rotation. In this way, the initial rotation is preserved.

I learned that all objects in C# are accesed by references. Correct me if I’m wrong but, in this case, we have two references pointing at the same object (“transform.rotation” and “originalRotationValue” pointing at the gameObject’s Quaternion object) so, if we change this Quaternion object using one reference, the other reference will see the last change made, isn’t it ?

This is not how it’s working in the posted code. In it, the “transform.rotation” Quaternion object is changed later but the “originalRotationValue” stays unchanged since it was initialized. (Because the author is able to effectively reset the rotation to its original value, represented by “originalRotarionValue”). This means that the “get” method of “transform.rotation” returns a copy (a clone) of its value (a new Quaternion) or something similar ?

Does the same happen with the rest of gameObject’s properties when we “get” them ?? I’m confused :frowning:

By the way, the code of the post works flawlessly. I used only as a reference for this question.

Quaternion is a struct, so you can’t actually reference it.

1 Like

Thank you for your reply.

So, does that mean that when we “get” a struct, we are always receiving a copy of it ?

Yes, that’s right.

1 Like

Thank you very much for your answer !!

1 Like

Structs default to passing by value. Classes default to passing by reference.

There are some weird exceptions to be aware of. You can force a struct to be passed by reference with the ref or out keyword. There are also immutable classes (like strings) that behave as if they were passed by value.