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

Unity中如何将Raycast射线命中的游戏对象添加至List列表

问题根因

你代码的异常来自Shoot方法内的列表添加逻辑错误:

  • GameObject.FindWithTag("Taggable")接口只会返回场景中第一个被标记为Taggable的对象,而非射线当前命中的对象,因此会出现每次点击都重复添加同一个对象的问题
  • 如果你此前误用了返回所有同标签对象的GameObject.FindGameObjectsWithTag接口批量添加,就会出现点击一次加入全部同标签对象的问题

修复方案

直接使用射线返回的命中对象添加到列表即可,可额外增加去重逻辑,避免同一个对象被重复加入列表,建议使用Unity官方推荐的CompareTag方法做标签判断,性能更优且不会触发空引用异常。

修复后完整代码

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerTagged : MonoBehaviour
{
    public float damage = 10f;
    public float range = 100f;
    public Camera fpsCam;
    public List<GameObject> playersTagged;

    private void Update()
    {
        if (Input.GetButtonDown("Fire1"))
        {
            Shoot();
        }
    }

    void Shoot()
    {
        RaycastHit hit;
        if (Physics.Raycast(fpsCam.transform.position, fpsCam.transform.forward, out hit, range))
        {
            Debug.Log(hit.transform.name);
            Target target = hit.transform.GetComponent<Target>();
            if (target != null)
            {
                target.takeDamage(damage);
                if (hit.collider.CompareTag("Taggable"))
                {
                    // 去重判断,避免同一对象重复加入列表
                    if (!playersTagged.Contains(hit.collider.gameObject))
                    {
                        playersTagged.Add(hit.collider.gameObject);
                    }
                }
            }
        }
    }
}

内容的提问来源于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 12:48:00