1.在场景中新建两个 Cube 立方体,在 Scene 视图中将两个 Cude的位置错开。
2.新建 C# 脚本 Distance.cs(写完记得保存)
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
-
- public class Distance : MonoBehaviour
- {
-
- public Transform objTrans1; //定义两个 Transform 组件变量
- public Transform objTrans2;
-
- // Start is called before the first frame update
- void Start()
- {
- //计算两个物体距离,使用 Vector3.Distance()
- float dis = Vector3.Distance(objTrans1.position, objTrans2.position);
- //输出到控制台
- Debug.Log("Distance = " + dis);
- }
-
- // Update is called once per frame
- void Update()
- {
-
- }
- }
3.将脚本绑定到场景中的主相机 Main Camera (将脚本拖到主相机上);然后将 Cube 和 Cube(1) 拖到主相机 Inspector 视图中的 Obj Trans 1 和 Obj Trans 2 中。

4.点击播放按钮,可以在 Console 视图中输出两个 Cube之间的距离(没有 Console 窗口按 Ctrl+Shift+C)
