I’m trying to add a feature where if the “z” key is hit, all enemies in a certain radius will be alerted. I think Physics.OverlapSphere is the best way to do this, but I cannot figure out how to implement it. I am using JS, and here are my scripts:
This is what I am using for pressing the ‘Z’ key, which causes the player to whistle
function Update () {
if (Input.GetKeyDown ("z"))
Whistle();
}
After Z is hit, all objects with the layer ‘Enemy’ that are within the radius of 100 should begin “AttackPlayer” - But I don’t know what I am doing wrong. I do not know how to search for ‘layer’ - I am just stabbing in the dark.
function Whistle()//added
{
var colliders : Collider[] = Physics.OverlapSphere(transform.position, 100.0);
for (var col : Collider in colliders)
{
if (col.collider.layer== "Enemy")
{
col.gameObject.SendMessage("AttackPlayer");
}
}
}
I thought “layer” is an int, not a string. Compare layer to LayerMask.NameToLayer(“Enemy”) instead. (optimize it later though after you get it working)
Using Layers would work well here but instead of checking the layer afterwards.
You can let the Physics.OverlapSphere call only return items of a specific layer.
What Joshimoo said. Create a public variable called enemyLayer : LayerMask, it will create a dropdown in the inspector that you can pick the enemy layer from. Then pass the mask into the OverlapSphere call.
var enemyLayer : LayerMask; //set this in the editor
function Whistle(){
var colliders : Collider[] = Physics.OverlapSphere(transform.position, 100.0, enemyLayer);
for (var col : Collider in colliders){
if (col.collider.layer== "Enemy")
col.gameObject.SendMessage("AttackPlayer");
}
}
If you just want to hard code it and you don’t want to set it as an inspector variable, you can use