Recently developing a racing game, game is fine but when i added traffic system (AI cars with waypoint following) the game becomes laggy ans slow. I used almost 300+ more cars with rigidbody and box collider attached.
I searched about solution of the problem :
Some said it’s the amount of rigidbnody or collider for making the game slow.
But if I remove colliders then I won’t be able to detect the collision between my main player’s car and AI traffic cars.
Any solution or suggestion ?
Problem Solved!
I used Unity Profiler to check the main cause of slowing the game. I found that I have a common script for the 300 traffic cars to follow a certain waypoints. That scripts updated every frame, that’s why the game became slow.
Solution :
-
I moved the waypoint follower code from Update function to LateUpdate, for this, the game doesn’t get hanged while starting the game cause LateUpdate always calls after all Update functions have been called.
-
Then I measured the distance between my Player car and each traffic cars, I take a minimum distance (in my case : 130m ) between Player car and a traffic car so that which traffic cars are away from this certain distance are inactive. I mean I make them active when they are in 130m range and make them inactive while they are not in that range.
And now my game becomes way faster!