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

Unity中如何将射线选中存入列表的对象在Tagger玩家碰撞时传送到指定位置

实现方案

你需要在Teleport类的触发判断逻辑中,遍历playersTagged列表,逐个修改列表内对象的位置即可,修改后的代码及配置说明如下:

修改后的Teleport类代码

using UnityEngine;

public class Teleport : MonoBehaviour
{
    public Transform teleportTarget;
    public PlayerTagged player;

    private void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.tag == "Tagger")
        {
            Debug.Log("You hit the can");
            // 非空判断避免运行时报错
            if (teleportTarget == null || player == null || player.playersTagged.Count == 0)
            {
                return;
            }
            // 遍历所有已标记对象执行传送
            foreach (GameObject taggedObj in player.playersTagged)
            {
                if (taggedObj != null)
                {
                    taggedObj.transform.position = teleportTarget.position;
                    // 如果对象挂载了刚体组件,清空速度避免传送后出现惯性偏移
                    Rigidbody rb = taggedObj.GetComponent<Rigidbody>();
                    if (rb != null)
                    {
                        rb.velocity = Vector3.zero;
                        rb.angularVelocity = Vector3.zero;
                    }
                    // 如果需要同步传送目标的旋转,取消下一行注释即可
                    // taggedObj.transform.rotation = teleportTarget.rotation;
                }
            }
            // 如果需要传送后清空已标记列表,取消下一行注释即可
            // player.playersTagged.Clear();
        }
    }
}

配置注意事项

  • 进入Unity Inspector面板,找到挂载Teleport脚本的对象,将场景内指定传送位置的Transform组件拖入teleportTarget字段,再将挂载了PlayerTagged脚本的对象拖入player字段
  • 确认所有可被标记的对象都已添加Taggable标签,触发碰撞的玩家对象已添加Tagger标签

内容的提问来源于stack exchange,提问作者Henrik Ferrari

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 15:48:04