Performance optimization tips: Physics in Unity | Tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
performance optimization tips physics and unity physics is an integral part of many games as game developers we often use physics to model reality or check when things collide when you start thinking about the code structure of your project and planning your design learning how physics simulation affects performance will help you avoid running into issues later on in your production in this video we'll go through some of the key physics considerations to keep in mind when you're aiming for maximum performance these tips will help you stay within the target frame rate while you're progressing from a prototype to a more complex project to learn more about physics best practices and to get an overview of the physics systems in unity visit the links in the description below physics simulation frequency first of all consider how often you need to run the physics simulation physics engines work by running on a fixed time step this means that the time between each physics step is exactly the same as the previous step by default unity runs the physics simulation at 50 hertz which is the equivalent to 50 frames per second to view the fixed rate that the project is currently running at go to edit project settings time the field fixed time step shows how long it takes to update between each interval a value of 0.02 is equivalent to an update rate of 50 hertz to change the update interval to 60 hertz we divide one with our target frame rate which would give us the time step of approximately 0.01667 while 50 hertz is the default you generally don't want physics to run multiple times per frame for example if the game logic ends up running for approximately 35 milliseconds the physics step will run twice as two simulations are required more physics steps means more work is needed to compute the simulation so it's important to set the fixed time step to be a value that is appropriate for our game if our game runs at 60 hertz having our physics step run at 50 hertz means that generally we'll perform one physics step per update on lower end devices it's possible to run into what is sometimes called the physics spiral of doom this occurs when our variable update loop takes too long to run and then multiple physics steps are needed to run to match the length of the long update loop in this case the main update loop and the physics update loop struggle to sync with one another performing wasted calculations and costing performance simulating manually we can also simulate our physics step manually by invoking physics.simulate for example if our game has a large spike due to a heavy load we can manually simulate our physics step such that it aligns more with the performance state of our game this allows us to have a situation-bound physics step if in the event we ever need it this also sidesteps having the physics engine trying to simultaneously perform multiple unneeded updates and causing performance issues in cases where we can predict that that may happen colliders colliders are the basis for defining the shape properties of our objects in the physics simulation we can define our physics shape to be a primitive such as a cube a sphere or a capsule or we can define a unique mesh to be the shape of our rendered object preparing data for mesh colliders physics engines usually run in two major steps the broad phase and the narrow phase the broad phase collects potential collisions that can happen and this data is sent to the narrow phase such that the collisions are actually computed when generating runtime meshes to use in the mesh collider it's important that generated meshes have properly created triangles meshes required by the physics engine will usually go through a process known as cooking which is a process that optimally builds the spatial structures for physics queries it's best to set the cooking options to produce faster results if you properly created a mesh with no degenerate triangles to do so you can disable options such as enable mesh cleaning weld co-located vertices and cook for faster simulation as of unity 2019.3 there's a new option known as the fast mid phase option that skips generating resource intensive archeries that were dominating the cooking time for meshes by default this option is enabled for all new projects additionally mesh cooking can be offloaded to another thread using the c-sharp job system to cook meshes on a different thread you can create an ijob parallel for job create a native array of instance ids and pass the number of meshes to operate per job in our bake mesh job we simply read the native array of mesh ids and call physics.bigmesh pruning for large scenes the physics engine works in two major steps the broad phase and the narrow phase the broad face attempts to efficiently determine the number of collisions which are needed for the narrow phase if you have many colliders then there are more potential collisions to check unity's physics engine uses a sweep and prune approach which can generate false positive collision pairs on generally flat worlds with many colliders in it to reduce the number of false positives you can switch the broad face type from sweep and prune broad phase to automatic box pruning this option can be found in edit project settings physics broad phase type automatic box pruning is similar to multi-box pruning except that it automatically determines the world boundaries and the number of grid cells in the world disabling automatic transform syncing when a transform is updated the transform is not automatically pushed to the physics engine transformation changes are accumulated to an array that is synced to the physics engine when needed by enabling the physics.autosync transform to true a sync point is then added before every query from the physics engine this can lead to a loss of performance if the transform component changes and then you perform physics queries such as raycasts and quick succession by default since unity 2017.2 physics.autosync transforms is disabled for all new projects colliders and rigid bodies while colliders generally define the shape of the body rigid bodies register the body to be influenced by unity's physics engine reuse the collision class instance unity exposes callback events in mono behaviors such as on collision enter on collision stay and on collision exit these callbacks generally have a collision instance as a parameter which is allocated on a managed heap because the collision instances are allocated on the managed heap they'll be collected by the garbage collector which can degrade performance to reduce the amount of garbage collected you can enable physics.reuse collision callbacks this will ensure that each callback invoked will receive a single instance of a collision pair you generally would only need to disable this option if the collision object is referenced outside of the collision callbacks for post-processing moving static colliders static colliders are generally considered game objects with a collider component and do not have a rigid body in their hierarchy in early versions of unity prior to unity 5 it was not advised to move static colliders because this regenerated the spatial tree for the broad face versions newer than unity 5 optimized the spatial tree rebuild for 3d physics in 2d physics it's still not generally a great idea to move a static collider as the tree rebuild is still time consuming also it's not a great idea to add a rigid body component to a static collider for the sole purpose of moving a physics body if all you intend to do is query against it instead you can translate the position of the physics body and allow the physics engine to accumulate the positional changes during its physics step if the physics body will interact in a more complex way it should still have a kinematic rigid body when moving a kinematic rigid body internally the physics engine will compute a velocity such that the rigid body moves over time during the physics step as such you should only add a kinematic rigid body if it is the behavior that you need for the game they are not needed for simply moving objects without complex physics behaviors using per body solver iterations sometimes we may need to have a more accurate simulation instead of increasing the simulation frequency by manipulating fixed delta time steps we can increase the number of solver iterations per rigid body you can access the solver iterations variable from a given rigid body and set a custom value this variable overrides the global default solver iterations static variable which can be inspected in edit project settings physics default solver iterations adjusting the per rigidbody solver iterations is generally fast since it's only applying additional computations to a single rigid body instance rather than all rigid bodies in the simulation raycasts and queries raycasts and other physics queries like overlap sphere or boxcast allow us to detect and collect colliders within a certain distance and direction use non-allocating queries any physics queries which return multiple instances of objects will allocate these objects on a managed heap this means that the garbage collector will eventually collect the allocated objects which can decrease performance if it happens at the wrong time to reduce the overhead of this it's generally recommended to use the non-alloc versions instead for example if you use an overlap sphere to collect all potential elements around a point it's better to use an overlap sphere non-allocal instead this allows you to create a fixed size array of colliders to store all queried colliders into the function finishes executing when there are no more colliders to collect or if the number of collected colliders reach the size of the buffer for example if we create an array of 10 colliders and there are 11 colliders around our point we would collect 10 out of the 11. therefore it's advisable to allocate a fixed size that is large enough for the situation you expect to encounter in the game use batch queries running queries immediately is very convenient when writing code however there are some downsides to this if you tend to have many colliders in the scene computing these queries on the spot may contribute to a significant amount of time being used to query there is an advanced option if you have a situation where you need to query a large number of colliders you can perform a batch query instead batch queries use unity's c-sharp job system and you can access this option through the raycast command api to use the raycast command we allocate a native array of raycast hits and a native array of raycast commands the raycast commands will store the origin the direction the collision layers to take into account and the number of max colliders the ray accounts for we call raycast command.schedule batch and pass in our native arrays of raycast commands and raycast hits the amount of work done per job and a job handle such that the scheduled job knows when to run if you don't need the query done immediately you can follow the concept of scheduling the job early and completing the job late this means you can complete the job by the start of the next frame by calling job handle dot complete physics can create intricate gameplay but has a performance cost when we know these costs we can tweak our physics behaviors to manage these costs appropriately and reduce any performance degradation that may occur to learn more physics optimization tips we highly recommend looking at the physics best practices page on unity learn and through the unity manual linked in the description box below thanks for watching
Info
Channel: Unity
Views: 41,088
Rating: undefined out of 5
Keywords: Unity3d, Unity, Unity Technologies, Games, Game Development, Game Dev, Game Engine, unity physics, unity perfomance, unity physics perfomance, unity profiles, unity physics tips, unity tips, unity tips physics, unity profiler tips, unity 2020 tips
Id: pTz3LMQpvfA
Channel Id: undefined
Length: 12min 38sec (758 seconds)
Published: Tue Mar 09 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.