Getting the closest GameObject to the player from an array
as the question implies... I need to get a GameObject from an array that's closest to the player so it can be destroyed.
Current Code (c#):
public GameObject[] myArray;
void Update(){
myArray = GameObject.FindGameObjectsWithTag("randomTag").OrderBy(go => go.transform.position.magnitude).ToArray();
}
void OnTriggerStay (Collider col) {
if (col.tag == "randomTag" && Input.GetButtonDown("randomButton")) {
Destroy(myArray[0]);
}
}
Quite Honestly, I have now Idea how to go about this... I don't know if it needs to be done in defining the array order (maybe like comparing the Vector3 magnitude with the player's Vector3 magnitude, the only reason I haven't tried that is because I don't know how) Or some ting like that.
Any how, any help would be greatly appreciated.
thx m8s
Answer by Firedan1176 · Jul 30, 2016 at 12:00 AM
void Update() {
myArray = GameObject.FindGameObjectsWithTag("randomTag");
}
void OnTriggerStay(Collider col) {
if(col.transform.CompareTag("randomTag") && Input.GetButtonDown(0)) {
GameObject closest = null;
foreach(GameObject g in myArray) {
if(Vector3.Distance(transform.position, g.transform.position) < Vector3.Distance(transform.position, closest.transform.position) || closest == null)
closest = g;
}
if(g == null) Debug.Log("No enemies have the tag were found.");
else Destroy(g);
}
}
Let me know how this works
Thanks! I don't have time at the studio to test it tonight, but just wanted to thank you for the quick response.
No problem. Let me know if it works. If this helped, please accept an answer. It adds to my self esteem and pride. :)
So, I tried it and assigned the proper tags and arrays and I trigger the event get an error saying: NullReferenceException: Object reference not set to an instance of an object
I feel like their should be an obvious answer to this, but as you probably guessed, I am still learning.