Find closest object and return this
Hello, the problem i have is that when my AI needs to find the closest gameobject (a tree) i'm getting a huge frame drop, i know why, but can't find a way to fix it.
At this moment when the tree spawns, it has a script (resource) based on the type its being added to a list with multiple tree's.
To get a tree my AI runs a foreach loop trough the list and looks at which tree is the nearest with Vector3.Distance, the tree that is closest to the AI will be returned and set as destination, but the only moment its going trough the list it's giving a huge frame drop, because the foreach loop loops trough an entire list of tree's.
The question:
How can i find the closest tree in a clean way?
Thanks in advance,
Answer by bubzy · Nov 12, 2015 at 12:26 PM
why not add all the vectors of the trees to an array or a list and just check distance against the list?
If the ai can cut the trees down or whatever, consider making a class for the tree so that you can check if the tree still 'exists'
Well, at this moment im adding the gameobject in the list, and check with the gamobject vector, which is the closest. Well the tree won't be cut down, for now maybe it won't depends on the time. The tree has a class:
Resource
in that class it's defined which type of resource it is.
yeah, but if you do this ONCE at the time the trees are instantiated, you will no longer have to continue to check them every time, you can just reference the list of vectors.
oh not i get it, but i still need to loop trough all vectors and calculate the distance, or is it still more resource friendy? I'm going to try out!
Your answer
Follow this Question
Related Questions
simplest way to add a minimum distance or gap between instantiated objects 1 Answer
Enemy watches player and shoots but bullets will not project.. 0 Answers
How do I make an AI(cube) that follows and rams the player? 0 Answers
A little doubt about creating a Talking BOT that simulates AI, for iOS system using Unity. 0 Answers