You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复Unity 2D C#中OnTriggerEnter2D触发传送无延迟问题

问题原因分析

  • 你猜测的传送对象错误问题确实存在:协程Wait()里的transform指代的是当前传送触发脚本挂载的物体(也就是传送门本身),而非进入触发区域的玩家对象,所以玩家不会被传送,反而会把传送门本身移走。
  • 延迟不生效的核心原因:你在触发时先把Time.timeScale = 0f,而WaitForSeconds的计时逻辑受时间缩放影响,时间缩放为0时,WaitForSeconds会永久暂停计时,永远不会执行后续逻辑。
  • 额外问题:代码里引用的UnityEditor.Experimental.GraphView是Unity编辑器专属命名空间,项目打包时会报错,需要删除。

修正方案

  1. 调整协程逻辑,将玩家的Transform作为参数传入协程
  2. 把WaitForSeconds替换为不受时间缩放影响的WaitForSecondsRealtime
  3. 修正传送对象为传入的玩家Transform,清理无效引用

修正后完整代码

using System.Collections;
using UnityEngine;

[RequireComponent(typeof(Collider2D))]
public class TeleportTrigger : MonoBehaviour
{
    public enum TriggerType { Enter, Exit };

    // 传送目标点
    [SerializeField] Transform teleportTo;
    // 触发对象标签筛选
    [SerializeField] string tag = "Player";
    // 触发时机
    [SerializeField] TriggerType type;


    void OnTriggerEnter2D(Collider2D other)
    {
        if (type != TriggerType.Enter)
        {
            return;
        }

        if (tag == string.Empty || other.CompareTag(tag))
        {
            Time.timeScale = 0f;
            // 将玩家对象的transform传入协程
            StartCoroutine(Wait(other.transform));
        }
    }

    private IEnumerator Wait(Transform playerTrans)
    {
        // 用不受timeScale影响的真实时间计时
        yield return new WaitForSecondsRealtime(5);

        // 传送玩家而非传送门本身
        playerTrans.position = teleportTo.position;
        Time.timeScale = 1f;
    }
}

补充说明

如果后续要加渐隐效果,可以在Time.timeScale = 0f之后、协程等待之前调用渐隐动画的播放逻辑,等待5秒的过程中可以完成渐隐、切换场景(如果需要)、渐显的流程,和当前的延迟逻辑完全兼容。

内容的提问来源于stack exchange,提问作者ItsByMe Lmao

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 00:06:04