- Home /
enemies in my Range
I am creating a combat script and i need some help.
I know that
float distance = Vector3.Distance(target.transform.position, transform.position);
gets the Distance between me and the target that i have selected.
now, how can I make all the object in that range my target. So, that I can get the script that they cary and change there health.
Answer by aldonaletto · Nov 03, 2011 at 12:42 AM
You could use Physics.OverlapSphere: it returns an array of all colliders that intersect an imaginary sphere of a given radius. You can then check the tags to know which ones are enemies, and apply the damage:
var cols: Collider[] = Physics.OverlapSphere(transform.position, radius); for (var col: Collider in cols){ if (col && col.tag == "Enemy"){ // if object has the right tag... var script: EnemyScript; // assuming the enemy script is called EnemyScript script = col.GetComponent(EnemyScript); script.health -= 5; // apply damage 5 } }Or, in C#:
Collider[] cols = Physics.OverlapSphere(transform.position, radius); foreach (Collider col in cols){ if (col && col.tag == "Enemy"){ // if object has the right tag... // assuming the enemy script is called EnemyScript EnemyScript script = col.GetComponent<EnemyScript>(); script.health -= 5; // apply damage 5 } }
Do you have it in C sharp? I understand it better that way.
I posted a C# version too. I'm a JS guy, thus this code may have awful C# errors!
Nitpicking- there's no point having the
if(col && col.tag == whatever)
thing all in one line- if 'col' returns null, 'col.tag' will always throw a null-reference-exception!
Other than that, your code is fine.
If col is null, the clause is false and the second condition is not tested - or at least it should not be; this was one of the great new ideas brought to the program$$anonymous$$g world by the C language. I suppose (and hope) that Unityscript and C# follow this rule.
Anyway, I suspect that col will never be null, but I saw this test in the AddExplosionForce example and decided not to risk.
Your answer
![](https://koobas.hobune.stream/wayback/20220613031218im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Detect if player is in range? 2 Answers
Gravity within range 1 Answer
How to use Sphere colliders to detect the "Player" 1 Answer
GetMouseButtonDown From a close distant 1 Answer
How To Properly Return An Object If Within Distance Range? 1 Answer