2

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,150
  • 8
  • 22
  • 37
  • 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

8

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
  • 35,446
  • 61
  • 386
  • 672