Copying target's XY position to object's XY position

Hello community,

So, as the title say, I want to copy the position from one target object to the specific object where I’ll put the script in. It’s in 2D so I don’t need the Z Axis, and I must not copy it because that will be the Z Axis of the camera over 2D area, that only works if it’s moved back (in the Z Axis) from the background. The target will be the player where Z=0. Anyways, it looks like this:

public GameObject target;

private Vector2 xy;
private Vector2 xyTarget;

void Start () {
	xy.x = transform.position.x;
	xy.y = transform.position.y;

	xyTarget.x = target.transform.position.x;
	xyTarget.y = target.transform.position.y;
} 

void LateUpdate () {
	xy.x = xyTarget.x;
	xy.y = xyTarget.y;
}

I assigned the target in the Inspector of course and the script has no compiler errors, but it doesn’t work. I can’t figure out what’s the problem and would like to fix this script. It would mean a lot to me to learn what’s the problem here.

P.S.
Yeah, I am pretty much a beginner :smiley:

Your not applying the position. In the late update try doing:

target.transform.position = transform.position;

this should set your targets position to the object the script’s on position.

you can do it vice versa if that’s what your trying to do

That way I would copy the whole position (Z Axis too, which I don’t want). Besides that, in LateUpdate it gives an error by writing it like this, because I need to store target.transform.position for example as variable.

Anyways, you gave me an idea to try something else and I fixed my code by writing it like this:

  [SerializeField] 
GameObject target;

private Vector3 xy;
private Vector2 xyTarget;

void Start () {
	xy.x = transform.position.x;
	xy.y = transform.position.y;
	xy.z = transform.position.z;
} 

void LateUpdate () {
	xyTarget.x = target.transform.position.x;
	xyTarget.y = target.transform.position.y;
	xy.x = xyTarget.x;
	xy.y = xyTarget.y;

	transform.position = xy;
}

So yeah. I had to put the part where I make (AND COPY) the Target position to the position of the object in the LateUpdate, because it has to be done every frame. In my case it didn’t work because it just copied variable to variable. I didn’t change anything else beyond that.

Thank you very much