首页 > 解决方案 > GetComponent 随机返回 null

问题描述

我正在尝试使用 Physics.OverlapSphere 获得具有一定半径的图层蒙版“僵尸层”的所有游戏对象对撞机。

我的问题有时是代码有效,有时当我尝试获取 Zombie AI 脚本组件时出现以下错误。我确保我所有的僵尸游戏对象都附加了 ZombieAI 脚本。

错误

这是代码:

public class SoundDetection : MonoBehaviour
{
    private float soundIntensity = 10f;
    public LayerMask zombieLayer;

    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            Detect();
        }
    }

    private void Detect()
    {

        Collider[] zombies = Physics.OverlapSphere(transform.position, soundIntensity, zombieLayer);

        if (zombies.Length == 0)
        {
            return;
        }
        else
        { 
            for (int i = 0; i < zombies.Length; i++)
            {
                zombies[i].GetComponent<ZombieAI>().OnAware(); //error here
            }
        }

    }
}

上面的代码位于我的 fps 控制器中的不同脚本中。如果我删除这个脚本并再次附加它,代码会一直工作,直到它由于某种原因随机停止。

我尝试查看其他解决方案,但由于我还是 Unity 3D 的新手,所以我什么也想不通。

任何想法我做错了什么?

标签: c#unity3d

解决方案


推荐阅读