transform.localPosition.Set isn't accurate?

Hi there :smile: I’m pretty new here, so correct me for any violations I might made in the question.
I’m going for an infinite 3D runner. Therefor, I’m trying to set my character’s position at certain X positions, e.g. turning to the left lane [this code is after the character reached localPosition.x = -1 value]:

xVelocity = 0; //transform's velocity.x
transform.localPosition.Set(-1f, transform.position.y, transform.position.z); //transform's position's X set to -1

Now, what really happens is my character stops moving due to the change of xVelocity [on each update I reset character’s velocity to a new vector containing xVel, yVel & zVel]; Nevertheless, the X position is set to where the character stops [unfortunately, it’s somewhere near -1.08 and not -1…], and doesn’t change to -1 afterwards.

Where am I mistaken? Thanks anyways :]

P.S. character isn’t a child of any other object.

localPosition is a property that returns a Vector3.

It is not a direct reference to the localPosition, but rather a struct copy.

You need to get and set it:

var v = transform.localPosition;
v.Set(-1f, transform.position.y, transform.position.z);
transform.localPosition = v;

Although, of course, in this situation this is a bit long winded when your’e effectively ‘Setting’ the position. Instead you can just say:

transform.localPosition = new Vector3(-1f, transform.position.y, transform.position.z);

Although, I’ll follow that up with a more logical issue. You’re copying the ‘position’ y and z, and setting them to the ‘localPosition’. This can cause for some weird results. Are you sure you mean to use ‘position.y’ and ‘position.z’???

3 Likes

There’s a discussion about it here:

2 Likes

Thanks for helping mate :slight_smile: Both of your solutions prevented unexpected position.x outcomes, even though it’s still stoping at -1.08. I know it’s unprofessional, but I can go on with that. And you’re right about the position, it’s just that my character isn’t really associated with an other object, so there’s no difference there.