You stumbled upon one of the very basic understanding problems of object oriented programming: Reference semantics.
There are two things that can happen when you say a = b
, and it depends on the type of the value being set.
For this problem, there are two categories of types: With reference semantics (class objects) and without reference semantics (primitives and structs).
A primitive, like a number, works like this:
int a = 10;
int b = a;
int b = 20;
print(a); // still 10
The value just gets copied over. When b is changed to 20, a is still 10. Same goes for structs, like Unity’s Vector3.
If you have an object instantiated from a class, the object gets created and then a reference to it is stored in a variable, not the object itself. So the same example with an object works differently:
Car car = new Car();
car.color = "red";
Car sameCar = car;
sameCar.color = "blue";
print(car.color); // it's blue now!
In this whole example, there’s only one car for the whole time, but two variables referencing it. When sameCar.color
is changed, that one car gets changed. And when you then ask for car.color
, it’s blue because it’s still that one same car we’re talking about.
Now what does this have to do with your problem?
“Transform” is a class, and every transform component in your scene is an object. Trying this:
gameObject1.transform = gameObject2.transform;
would mean that gameObject1 should forget about the transform component it has and instead consider gameObject2’s transform component as its own. Just like when changing car colors, this would mean that moving gameObject2 would move gameObject1 as well, and vice versa.
This is not what anybody would want to happen, so GameObject.transform is read-only. You cannot delete or replace a GameObject’s transform component. But what you can do is change its values since those are Vector3s and Quaternions, which are structs and thus get copied over.
var t1 = gameObject1.transform; // Note how in these two lines we are actually
var t2 = gameObject2.transform; // using it to out advantage that it's still the same object
t1.position = t2.position;
t1.rotation = t2.rotation;
t1.localScale = t2.localScale;