Abstract Path planning for the unmanned aerial vehicle (UAV) is to assist in finding the proper path, serving as a critical role in the intelligence of a UAV. In this paper, a path planning for UAV in three-dimensional environment (3D) based on enhanced gravitational search algorithm (EGSA) is put forward, taking the path length, yaw angle, pitch angle, and flight altitude as considerations of the path. Considering EGSA is easy to fall into local optimum and convergence insufficiency, two factors that are the memory of current optimal and random disturbance with chaotic levy flight are adopted during the update of particle velocity, improving the balance between exploration and exploitation for EGSA through different time-varying characteristics. With the identical cost function, EGSA is compared with seven peer algorithms, such as moth flame optimization algorithm, gravitational search algorithm, and five variants of gravitational search algorithm. The experimental results demonstrate that EGSA is superior to the seven comparison algorithms on CEC 2020 benchmark functions and the path planning method based on EGSA is more valuable than the other seven methods in diverse environments.