I'm trying to get all colliders of game objects with a layer mask "Zombie Layer" with a certain radius using Physics.OverlapSphere.
My problem is sometimes the code works and sometimes the I get this error below when I try to get the Zombie AI script component. I've ensured that all my zombie game objects have the ZombieAI script attached to them.
Here is the code:
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
}
}
}
}
The above code is in a different script placed in my fps controller. If I remove this script and attach it again, the code works until it stops randomly for some reason.
I tried looking at other solutions but couldn't figure anything out since I'm still new to Unity 3D.
Any ideas what I'm doing wrong?