Floating-point errors while assigning transforms

In my hierarchy, I have:

  • Main camera
  • Empty game object named “Level”

I’ve also created and attached a simple script to Level which is meant to load dungeon tile prefabs, generate a tilemap, and lay out the tiles in 3D space to make a seamless dungeon. The problem is, whenever I programmatically assign a position, rotation or scale to any given tile, I get massive floating-point errors between 0.00001 and 1.3, which leaves a visually noticeable unaligned tile layout.

I have even tried explicitly casting these values into integer values, checking in the debugger that they are indeed the expected values, and yet, after assigning them to a transform, they still show up slightly off in the inspector. However, when launching the script and then manually setting these values within the inspector, all the tiles line up perfectly and everything looks as expected. So the issue only occurs when assigning values to transforms within a script…

What is the cause of this madness, and what can be done to fix it?

Since manually setting the transform in the inspector always seems to fix this issue, I have found a temporary solution for anyone else who might be looking for one…

  • In the project explorer, select any prefab (such as a wall)
  • Hold the Alt key, and drag the prefab into the same folder. This will create a copy.
  • Rename your copy using whatever naming convention works for you (I just did “wall_0”, “wall_1”, etc)
  • For “wall_1”, set the Y-rotation to 0 in the inspector. Increment this value by 90 for “wall_1”, then repeat this process until you have 4 prefabs, each with a Y-rotation 90 degrees higher than the previous copy.

… Now you can instantiate your prefabs in any script, simply using whatever naming convention you chose, without having to worry about floating-point errors messing up your transforms. Unfortunately, this solution only accounts for rotations. If floating-point errors are visually messing up your translations, you will need to find some other solution.