How can I convert float to int?

cube1.name = string.Format("Terrain_{0}_{1}", 
    (int)Terrain.activeTerrain.transform.position.x + tilePositionInLocalSpace.x, 
    (int)Terrain.activeTerrain.transform.position.z + tilePositionInLocalSpace.y);

Tried to cast it for int but it didn't change much. The name of each cube is still for example: Terrain_6.5_5.5. But I want the name to be Terrain_6_5.

tilePositionInLocalSpace is vector3 type and both x are float type.

Jon Skeet
people
quotationmark

You've just got a precedence problem. You've got:

(int) x + y

which is equivalent to

((int) x) + y

... which will then promote the result of the cast back to a float in order to perform floating point addition. Just make the cast apply to the whole result instead:

(int) (x + y)

Where x and y are the rather long expressions in your original code, of course. For the sake of readability, I'd extract the two values to separate local variables, so you'd have:

int sumX = (int) (Terrain.activeTerrain.transform.position.x + tilePositionInLocalSpace.x);
int sumY = (int) (Terrain.activeTerrain.transform.position.z + tilePositionInLocalSpace.y);
cube1.name = string.Format("Terrain_{0}_{1}", sumX, sumY);

Or better still:

var position = Terrain.activeTerrain.transform.position;
int sumX = (int) (position.x + tilePositionInLocalSpace.x);
int sumY = (int) (position.z + tilePositionInLocalSpace.y);
cube1.name = string.Format("Terrain_{0}_{1}", sumX, sumY);

people

See more on this question at Stackoverflow