How to move one object to the exact position of another object?

I'm attempting to move one object to the exact position of another object, but I'm having weird issues with it. ObjectA is the object being moved; it has no parent. ObjectB has parents. I would think it would be as simple as:

ObjectA.transform.position = ObjectB.transform.position;

When I attempt this though, ObjectA is never on target. Any ideas on what I'm missing?

Setting `transform.position` moves the pivot of the object (the local origin). Could it be that the pivots of ObjectA and ObjectB are not in the same place. Alternatively, could it be that the pivots of the objects are not at the center of the model, so that when ObjectA and ObjectB has different orientation it looks like they are not in the same position? Try setting the rotation as well

ObjectA.transform.rotation = ObjectB.transform.rotation;

EDIT: Complete answer redo!


ObjectB's transform is, indeed, relative to its parents. Its Vector3 coordinates are relative to its parent's location, so the reason your code isn't working correctly is because ObjectA is transforming to the correct location in worldspace, and its coordinates are relative to 0,0,0. However, ObjectB's coordinates are relative to the position of its parents, treating its parent's location as 0,0,0, which, understandbly causes problems, for if you set the transform of each object to 0,0,5, and ObjectB's parent is already at 0,0,5, ObjectB will treat its parent's location as 0,0,0, causing it to be offset by 10, instead of 5. This will cause its location to differ from ObjectA's. Use this code to translate relative space to worldspace:

var ObjectBPosition = function TransformDirection (0, 0, 0);

Put this code on ObjectB and save it as ObjectBCode.js. The next code goes on ObjectA.

var ObjectBCode : ObjectBCode;

function Update () {
    transform.position = (ObjectB.ObjectBPosition.x, ObjectB.ObjectPosition.y, ObjectB.ObjectPosition.z);
}

Put this code on ObjectA and drag ObjectB (with ObjectBCode attached) onto the open slot in the Inspect. Press play.

Look at this script bellow and attach it to an empty game object:

var object1 : GameObject;

var object2 : GameObject;

function Update () {

//Check if player hit left mouse button (default for Fire1)
if (Input.GetButtonDown("Fire1")){

//Stores position and rotation of one of the objects
var position1 : Vector3 = object1.transform.position;
var rotation1 : Quaternion = object1.transform.rotation;

object1.transform.position = object2.transform.position;
object1.transform.rotation = object2.transform.rotation;

object2.transform.position = position1;
object2.transform.rotation = rotation1;

}

}

The example above is one of the correct ways to define a position based on another object's position.

Hope that helps.