- Home /
How to round the coordinates of a game object to an integer or "nice" number?
I am trying to make a very basic snap to grid (and only on the X axis) but the Round function isn't quite working for me.
void Update () { Mathf.RoundToInt(transform.position.x); }
I was wondering if there's another way, or I'm just doing something wrong here?
Can you explain more "isn't quite working for you" mean? Or give more info about ur problem? AFAI$$anonymous$$ the $$anonymous$$athf.RoundToInt is acceptable in this case (I mean round case). The only thing I think I have to mention you is this special case:
If the number ends in .5 so it is halfway between two integers, one of which is even and the other odd, the even number is returned.
Answer by Bunny83 · Dec 15, 2017 at 05:01 AM
Yes, you do something wrong here. RoundToInt is a method that returns the rounded value as integer. In your code you don't do anything with the returned value. If you want to actually move the objects to the rounded position you have to do this:
Vector3 tmp = transform.position;
tmp.x = Mathf.Round(tmp-x);
transform.position = tmp;
Note that you have to use an actual temporary variable as you can't directly change only one component of transform.position as it's a property (getter and setter combo) and Vector3 is a valuetype.
Also note that i did not use RoundToInt as this would be pointless. A Vector3 consists of floating point numbers. So you could use RoundToInt but it would have to convert the returned integer back to a float anyways. So just using Round is enough.
If the question is answered you should accept the answer.
Your answer
![](https://koobas.hobune.stream/wayback/20220612144620im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How to fix child gameobject position in relation to sphere parent transform. 1 Answer
image prefab transform does not work 0 Answers
Use OnTriggerEnter during a transform ! 0 Answers
Issues with commands regarding the Udemy guide 0 Answers
Changes of Transform cancel on next frame after change 1 Answer