[英]Unity: Distance between two game-objects in the scene view
I am new to Unity and as I am creating my interface, I am trying to find what's the distance between two game objects.我是 Unity 的新手,在创建界面时,我试图找出两个游戏对象之间的距离是多少。 I know how to do in a C#/javascript script, however I am strugling to find this information in the scene view.
我知道如何在 C#/javascript 脚本中执行操作,但是我很难在场景视图中找到此信息。 Any key I could press while moving an object to see the distance to its neighbours ?
移动一个物体时我可以按什么键来查看到它的邻居的距离?
In a script, you can use Vector3.Distance between vector3 to get the distance between two points.在脚本中,您可以使用Vector3.Distance between vector3 来获取两点之间的距离。 Every gameObject has a position that is represented in a Vector3.
每个游戏对象都有一个在 Vector3 中表示的位置。
Below is a script example that shows you how it works.下面是一个脚本示例,向您展示了它是如何工作的。 You just have to drag the script onto a gameObject in your scene and drag in the inspector another gameobject in your scene.
您只需将脚本拖动到场景中的游戏对象上,然后在检查器中拖动场景中的另一个游戏对象即可。 The script should run even when your not in play mode because of the [ExecuteInEditMode].This way you will see the distanceBetweenObjects update in real time without actually having to hit play.
由于 [ExecuteInEditMode],即使您不在播放模式下,脚本也应该运行。这样您将看到 distanceBetweenObjects 实时更新,而无需实际点击播放。
using UnityEngine;
[ExecuteInEditMode]
public class DistanceBetweenTwoObjects : MonoBehaviour
{
public GameObject obj;
public float distanceBetweenObjects;
private void Update()
{
distanceBetweenObjects = Vector3.Distance(transform.position, obj.transform.position);
Debug.DrawLine(transform.position, obj.transform.position, Color.green);
}
private void OnDrawGizmos()
{
GUI.color = Color.black;
Handles.Label(transform.position - (transform.position -
obj.transform.position)/2, distanceBetweenObjects.ToString());
}
}
The method OnDrawGizmos will draw text in between the 2 objects showing the distance value to help make it more user friendly. OnDrawGizmos 方法将在显示距离值的 2 个对象之间绘制文本,以帮助使其更加用户友好。
There isn't any built-in functionality for this, but it's fairly trivial to add such a readout into the display using [ExecuteinEditMode], which causes scripts to run even when the game is not in play mode.对此没有任何内置功能,但使用 [ExecuteinEditMode] 将此类读数添加到显示中是相当简单的,即使游戏未处于播放模式,脚本也会运行。 This script, for example, should readout the distances on different axes and in total:
例如,这个脚本应该读出不同轴上的距离和总计:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[ExecuteInEditMode]
public class EditorDistanceDisplay : MonoBehaviour
{
public GameObject target1;
public GameObject target2;
public float distanceX;
public float distanceY;
public float distanceZ;
public float distanceTotal;
void Start()
{
}
void Update()
{
Vector3 delta = target2.transform.position - target1.transform.position;
distanceX = delta.x;
distanceY = delta.y;
distanceZ = delta.z;
distanceTotal = delta.magnitude;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.