Why does (GO).transform.position.Set(x,y,z); not work, while (GO).transform.position = new Vector3(x,y,z) does?
Just as the title says.
I understand 'position' gives you the copy of actual location of the object which is why (GameObject).transform.position.Set(x,y,z) does nothing useful because only thing it does is changing the vectors of the copied. And the same thing goes to (GameObject).transform.position.x(y or z) = 0.5f; and such.
What I don't understand is, if that's the case why (GameObject).transform.position = new Vector3(x,y,z); works? As far as I know "new Vector3" is but a struct composed of (x, y, z) values and storing its values into copied position should yield the same result as the above. I've googled a bit but couldn't quite find the answer I was looking for. Please help.
Answer by Hellium · Feb 19, 2019 at 10:09 AM
As you have indicated, when calling Debug.Log( transform.position )
, you call the getter returning a copy of the position. The same happens when calling transform.position.Set( x, y, z )
(you call the Set
function on the copied vector returned by the property).
However, when you write transform.position = new Vector( x, y, z )
, you are assigning a value, thus, calling the setter of the position
property.
This is handled in the C++ part of the engine. In C# you can reproduce this behaviour as follow:
private Vector3 _position;
public Vector3 position
{
get { return new Vector3( _position.x, _position.y, _position.z ); }
set { _position = value ; }
}
Thank you for the reply. Your explanation makes perfect sense and now I can see what's really going on with the 'position' property. Really appreciated!
Your answer
Follow this Question
Related Questions
The type or namespace function could not be found 1 Answer
Words in my script don't turn blue, why not? (absolute script noob) 3 Answers
GameObject.Find : why not working? 3 Answers
How to add information to an instantiated object 0 Answers
Merge Points collection system via a separate script 0 Answers