3

I instantiate an object on a mouse click. I need to get transform position x and y upto 3 decimal places. Here is my code.

void OnMouseDown()
    {
        ray=Camera.main.ScreenPointToRay(Input.mousePosition);

        if(Physics.Raycast(ray,out hit))
        {

            if(Input.GetKey(KeyCode.Mouse0))
            {
                GameObject obj=Instantiate(prefab,new Vector3(hit.point.x,hit.point.y,hit.point.z), Quaternion.identity) as GameObject;
                OrbsList.Add(new Vector3(obj.transform.position.x,obj.transform.position.y,0));
            }

        }
    }

Right now if a obj is instantiated at position (4.53325, 3.03369, 0) it is saved as (4.5,3.0,0). I want to save it's position as (4.53325, 3.03369, 0). Please help thanks.

Sameer Hussain
  • 2,421
  • 8
  • 23
  • 41
  • 5
    It is saved where you want it to be, it is just the display that is simplified. – Everts May 11 '16 at 12:01
  • @Everts Oh you are right. I just converted x and y to string and they show exact positions not rounded off. Thanks and i feel stupid now – Sameer Hussain May 11 '16 at 12:07
  • careful, floats only have a limited precision and the values you use here are precice enough to not show the desired results once you use them in calculations. – yes May 11 '16 at 12:34

1 Answers1

9

For the record, Debug.Log annoyingly prints only one decimal place.

Do this

Vector3 pos = obj.transform.position;
Debug.Log("pos x is now " + pos.x.ToString("f3"));
Debug.Log("pos y is now " + pos.y.ToString("f3"));
Debug.Log("pos z is now " + pos.z.ToString("f3"));

BUT NOTE!

There's good news: Unity sensibly added "ToString" to Vector3. So, you can just do this:

Vector3 pos = obj.transform.position;
Debug.Log("pos is now " + pos.ToString("f3"));

Fortunately it's that easy.


For anyone reading who is a new programmer, this is a great opportunity to learn about extensions. Quick extensions tutorial.

public static class Handy
   {
   public static float Say(this GameObject go)
      {
      Debug.Log(go.name + ", position is ... "
             + go.transform.position.ToString("f3");
      }

So now you can do this...

 obj.Say();

...anywhere in your project.

Community
  • 1
  • 1
Fattie
  • 27,874
  • 70
  • 431
  • 719
  • is there a way to do it without casting it to string first ? – Maciek Woźniak Oct 18 '22 at 14:35
  • 1
    @MaciekWoźniak (1) you can simply Debug.Log("hello " + c); (2) you can also: Debug.Log($"hello {x}"); But if you WANT THE FORMATTING (re-read the first sentence of this answer) you have to do what it says in the answer. All the best – Fattie Oct 18 '22 at 15:58