我在单击鼠标时实例化了一个对象。我需要将变换位置 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));
}
}
}
现在如果一个对象在位置 (4.53325, 3.03369, 0) 被实例化,它被保存为 (4.5,3.0,0)。我想将它的位置保存为 (4.53325, 3.03369, 0)。请帮忙谢谢。
请您参考如下方法:
作为记录,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"));
但请注意!
有个好消息:Unity 明智地将“ToString”添加到 Vector3。所以,你可以这样做:
Vector3 pos = obj.transform.position;
Debug.Log("pos is now " + pos.ToString("f3"));
幸运的是,这很容易。
对于阅读本书的新程序员来说,这是了解扩展 的绝佳机会。 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");
}
所以现在你可以这样做了......
obj.Say();
...您项目中的任何位置。
