在 unity 中获取最多 3 个小数位的对象位置

Sam*_*ain 2 c# unity-game-engine

我在鼠标单击时实例化一个对象。我需要将 x 和 y 转换位置最多保留 3 个小数位。这是我的代码。

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));
            }

        }
    }
Run Code Online (Sandbox Code Playgroud)

现在,如果 obj 在位置 (4.53325, 3.03369, 0) 处实例化,则将其保存为 (4.5,3.0,0)。我想将它的位置保存为 (4.53325, 3.03369, 0)。请帮忙谢谢。

Fat*_*tie 7

为了记录,Debug.Log烦人地只打印一位小数。

做这个

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"));
Run Code Online (Sandbox Code Playgroud)

但请注意!

好消息是:Unity 明智地向 Vector3 添加了“ToString”。所以,你可以这样做:

Vector3 pos = obj.transform.position;
Debug.Log("pos is now " + pos.ToString("f3"));
Run Code Online (Sandbox Code Playgroud)

幸运的是,这很容易。


对于任何阅读此书的新程序员来说,这是了解扩展的绝佳机会。快速扩展教程

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

所以现在你可以这样做......

 obj.Say();
Run Code Online (Sandbox Code Playgroud)

...在您的项目中的任何地方。