How to find nearest game object ?

You could do Physics.OverlapSphere to find nearby colliders, but in this case it might be stupid.
For case like this you should create some custom managers and depending on your case you might need jobs or some segmentation of the map to avoid checking every single bush.

The most simple (but a bit ugly) solution would be to create Bush script with static list of all bushes. Next, when you need to find closest bush you would call static method FindClosestBush() and check distance between some position and all bushes and pick the closest one. Also there is no need to calculate exact distance, you can compare it using distance squared. Something like this:

public class Bush : MonoBehaviour
{
    // List of all bushes
    private static List<Bush> instances = new List<Bush>();

    public static Bush FindClosestBush(Vector3 position)
    {
        // Iterate all bushes and compare distance
        for (int i = 0; i < instances.Count; i++)
        {
            Bush bush = instances[i];
            float sqrDistance = (bush.transform.position - position).sqrMagnitude;
            // TODO: Compare distance between bush and current closest bush
            if (sqrDistance < ?)
            {
                // TODO: Cache current closest to compare with next one
            }
        }
        // TODO: return position of the closest bush
        // return closestBush;
    }

    private void OnEnable()
    {
        // Add bush when active
        instances.Add(this);
    }

    private void OnDisable()
    {
        // Remove bush when not active
        instances.Remove(this);
    }
}

// edit: There are plenty resources on google, like this one , but I’m gonna assume you are scared of checking all bushes will be very slow. Even if there are 100 villagers doing bush check, then most likely not all of them do it at the same time, so one check per few frames is not so bad. If there is possibility that all of them can do it at the same time, then you can create some scheduler/manager to limit queries to X per frame (or use jobs) - this is what navmesh does.

1 Like