Find nearest gameobject with tag

So I have a game where you can assign professions to workers. One of those is a lumberjack. I need workers with this tag to find the nearest object with tag WorkWood, which I used to mark trees. I have the movement, rotation, chopping and inventory all sorted out. I’m very new to coding and all of the google searches, youtube tutorials and rummaging through the unity api and forums has gotten me nowhere. In the scene, I have 3 workers, 3 trees and a place for them to leave the wood they collect, as well as other stuff, and I need each individual worker to be able to find, of all of the objects in the scene, the nearest tree. Thanks in advance!


You can use GameObject.FindGameObjectsWithTag to find your trees and run a foreach loop checking the distance of each with Vector3.Distance and then picking the lowest.

If you’re worried about performance (FindGameObjectsWithTag is kind slow), you could instead store some array of all the trees and search that instead.

Hope this helps!