I want to use Physics.OverlapSphere to select the closest enemy when pressing tab. I surfed the web for hours but all the script I found where in js.
There’s a good C# example in the docs, but in [Rigidbody.AddExplosionForce][1] - the Physics.OverlapSphere example isn’t so good. You can have a function that finds the nearest enemy inside a sphere of the given radius, or null if none:
Transform FindNearestEnemyInSphere(float radius){ float minDist = Mathf.Infinity; Transform nearest = null; Collider[] cols = Physics.OverlapSphere(transform.position, radius); foreach (Collider hit in cols) { if (hit && hit.tag == "Enemy"){ float dist = Vector3.Distance(transform.position, hit.transform.position); if (dist < minDist){ minDist = dist; nearest = hit.transform; } } } return nearest; } // you can call the function above in Update: void Update() { if (Input.GetKeyDown("tab")){ Transform enemy = FindNearestEnemyInSphere(6.0f); if (enemy){ // do whatever you want with your enemy } } }
The usual warning: I’m a JS guy, thus the code above may contain some C# stupid errors.
EDITED: If you want to select and deselect more than one enemy, it’s better to use a list. I’ve never used lists, but I guess you should declare the appropriate namespace in the heading:
using System.Collections.Generic;
Then you should declare the list and change your code to use it:
Transform FindNearestEnemyInSphere(float radius){ ... // nothing change in this function } List selected = new List(); // declare the list void Update() { if (Input.GetKeyDown("tab")){ Transform enemy = FindNearestEnemyInSphere(6.0f); if (enemy){ selected.Add(enemy); // add enemy to the "selected" list // do other selection stuff, like changing color etc. } } if (Input.GetKeyDown("keyUsedToDeselect") && selected.Count > 0){ // find the farthest enemy in the list float maxDist = Mathf.NegativeInfinity; int far = 0; for (int i = 0; i < selected.Count; i++){ float dist = Vector3.Distance(transform.position, selected*.position);* *if (dist > maxDist){* *maxDist = dist;* *far = i;* *}* *}* *Transform deSelEnemy = selected[far]; // get a reference to the deselected enemy* *selected.RemoveAt(far); // remove element from the list* *// do other deselection stuff, like restoring color etc.* *}* *}* **
[1]: http://unity3d.com/support/documentation/ScriptReference/Rigidbody.AddExplosionForce.html