Unity中如何实时显示列表内距离玩家最近的Spreaded Fire对象?
Unity 实时显示最近火焰对象及距离的功能修正
需求说明
通过TextMeshProUGUI实时展示距离玩家最近的Spreaded Fire对象及其距离,玩家移动时需同步更新为当前最近目标。
原有脚本的问题
- 第一段脚本在Update循环中逐个覆盖文本内容,最终仅显示最后一个火焰的距离,未实现“最近”筛选逻辑。
- 第二段脚本使用
oldDistance对比,但未在每次Update时重置该值,导致一旦找到一个较近目标后,只有当出现更近的目标时才会更新,无法在玩家移动后重新计算全局最近的对象,因此切换极不稳定。
修正后的完整脚本
using System.Collections.Generic; using System.Linq; using TMPro; using UnityEngine; public class SpreadedFireDistanceCheck : MonoBehaviour { public TextMeshProUGUI distanceText; public GameObject player; private List<GameObject> spreadedFires = new List<GameObject>(); void Start() { // 初始化获取所有带"Spreaded Fire"标签的对象 spreadedFires = GameObject.FindGameObjectsWithTag("Spreaded Fire").ToList(); } void Update() { // 处理无火焰对象的情况 if (spreadedFires.Count == 0) { distanceText.text = "No fires detected"; return; } // 初始化最近目标和距离 GameObject nearestFire = spreadedFires[0]; float nearestDistance = float.MaxValue; // 遍历所有火焰,找到最近的那个 foreach (var fire in spreadedFires) { // 跳过已被销毁的对象,避免空引用错误 if (fire == null) continue; float currentDistance = Vector3.Distance(player.transform.position, fire.transform.position); if (currentDistance < nearestDistance) { nearestDistance = currentDistance; nearestFire = fire; } } // 更新UI,显示火焰名称和保留两位小数的距离 distanceText.text = $"Nearest Fire: {nearestFire.name}\nDistance: {nearestDistance:F2} units"; } }
关键修正点
- 全局重新计算:每次Update都重新初始化最近距离为极大值,遍历所有火焰对象,确保找到当前帧真正的最近目标。
- 空引用防护:加入
if (fire == null)判断,避免火焰对象被销毁后引发的空引用异常。 - UI体验优化:显示火焰对象的名称(比索引更直观),距离保留两位小数,提升可读性。
- 边界场景处理:当场景中没有火焰对象时,显示明确的提示文本。
内容的提问来源于stack exchange,提问作者Daniel Lip
相关产品推荐
相关产品推荐

