c# - 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 的新手,所以我什么也想不通。
任何想法我做错了什么?
解决方案
推荐阅读
- amazon-web-services - 如何从 GCP vm 实例向 AWS SES 发送电子邮件
- javascript - 我想使用 Next.js API 路由将图像上传到 Imgur
- nginx - 从 Laravel 中的 curl 请求中获取标头
- flutter - 在 vsCode 中格式化 .dart 文件(颤振)
- flutter - Flutter Update 2.0.6 以前的库(如 Expanded、ListView 等)的问题
- android - 如果发布构建机器发生更改,我们是否需要重新生成和更新密钥库和别名?
- node.js - 我无法从 nodejs 应用程序中的 mongodb 快速检索文件
- heroku - 如何在 Hostinger 上托管 Heroku DNS
- http - Apache HTTP 代理为某些目标 IP 工作并从其他目标接收 502 Bad Request
- jmeter - JMeter 使用 ForEach 控制器并行执行