How to check distance between a specific object and every objects in a list ?,How can I check the distance between an object and every objects in a list ?
First of all, I'm really new to coding, so I don't have any references or bases of some sort.
I'm trying to prevent a specific object, controlled by the player to get too close of any objects in the list called "OtherTraps".
public float Counter; public bool Timing = false; public List<GameObject> OtherTraps = new List<GameObject>(); void Start() { OtherTraps.AddRange(GameObject.FindGameObjectsWithTag("PiègeActif")); }
This list is composed of every objects having a specific tag. I'm trying to compare the distance between the object and every listed objects. I tried this :
for (int i = 0; i <= OtherTraps.Count; i++) { if (transform.position.x - this.transform.position.x >= 5) { transform.position += new Vector3(1, 0, 0); } }
Obviously it didn't work so I'm looking for help here.
Answer by Mr_parkour10021 · Feb 05, 2019 at 09:20 PM
@OnlyOne01 use a foreach
loop. the syntax is like this: foreach(DataType name in yourList) { // DoSomething }
so basically in your case it would be foreach(GameObject obj in OtherTraps) { // Checks if the gameobject that this script is on is close to any of the objects in your list if(Vector3.Distance(transform.position, obj.transform.position) < distanceBetweenObject) { // your code goes here } }
i hope i could help!
Your answer
Follow this Question
Related Questions
Get the lowest value from a Gameobject List 0 Answers
Check if a large number of gameobjects are colliding 1 Answer
Transport gameobjects with photon 0 Answers
Shake GameObject in 0 Answers