Unity中嵌套循环实现有序物体传送位置失效问题求助
问题原因
你的代码逻辑本身没写错,但OnTriggerEnter是在一帧内执行完成的,嵌套循环会瞬间把所有位置赋值都跑完,物体的位置会被最后一次循环的结果覆盖——你的数组最后一个元素是3,所以直接跳到SP3,中间的传送过程因为太快根本看不到。
解决方法
用Unity的协程(Coroutine)给每个传送步骤加延迟,让物体按顺序逐个移动。修改后的代码如下:
public class Teleporting : MonoBehaviour { public GameObject mouse; public Transform SP1; // 赛道1起点 public Transform SP2; // 赛道2起点 public Transform SP3; // 赛道3起点 private int[,] track_teleportation_index; void OnTriggerEnter(Collider other) { // 提前赋值mouse,避免每次Find(如果Inspector已经拖了可以直接去掉这行) if (mouse == null) mouse = GameObject.Find("mouse"); track_teleportation_index = new int[3, 3] { { 1,2,3 }, { 3, 1, 2 }, { 1, 2, 3 } }; // 启动协程执行分步传送 StartCoroutine(TeleportInSequence()); } IEnumerator TeleportInSequence() { // 遍历二维数组的每个元素 for (int row = 0; row < track_teleportation_index.GetLength(0); row++) { for (int col = 0; col < track_teleportation_index.GetLength(1); col++) { int trackNum = track_teleportation_index[row, col]; // 根据trackNum设置位置 switch(trackNum) { case 1: mouse.transform.position = SP1.position; break; case 2: mouse.transform.position = SP2.position; break; case 3: mouse.transform.position = SP3.position; break; } Debug.Log("传送到赛道 #" + trackNum); // 等待1秒(可以改成你需要的延迟时间,比如0.5f就是半秒) yield return new WaitForSeconds(1f); } } } }
额外优化建议
- 不要在OnTriggerEnter里每次都用
GameObject.Find,可以直接在Inspector面板把mouse拖到脚本的public字段里,效率更高。 - 用switch替代if-else,逻辑更清晰,尤其是后续扩展更多赛道时。
- 延迟时间可以做成public变量,方便在Inspector里调整,不用改代码。
内容的提问来源于stack exchange,提问作者jyeo3159
相关产品推荐
相关产品推荐

