- Home /
Help with optimize code
Hello! I would like to ask you to help me with optimize my code of course if it is possible. It is a vehicle wheel. Vehicle has 4 wheels. On scene there is 769 vehicles. With that amount of vehicles I have 60 fps. Profiler says that the worst is SpringAndDamping then ForwardFriction and SideFriction. Is it possible to optimalize this code?
private void FixedUpdate()
{
velocity = (myTransform.position - prevPos) / Time.deltaTime;
wheelVel = myTransform.InverseTransformDirection(velocity);
SpringAndDamping();
ForwardFriction();
SideFriction();
prevPos = myTransform.position;
}
private void SpringAndDamping()
{
if (IsGrounded == false) return;
Vector3 up = myTransform.up;
Vector3 pos = myTransform.position;
vehicleRigidbody.AddForceAtPosition(up * (springForce * forceMultiple.Evaluate(Mathf.Lerp(1, 0, Vector3.Distance(pos, hitPoint) / wheelDistance))), pos, ForceMode.Acceleration);
vehicleRigidbody.AddForceAtPosition(up * (dampingForce * (-wheelVel.y)), pos, ForceMode.Acceleration);
}
private void ForwardFriction()
{
if (IsGrounded == false) return;
vehicleRigidbody.AddForceAtPosition(myTransform.forward * (forwardFriction * (-wheelVel.z)), myTransform.position, ForceMode.Acceleration);
}
private void SideFriction()
{
if (IsGrounded == false) return;
vehicleRigidbody.AddForceAtPosition(myTransform.right * (globalFriction * (-wheelVel.x)), myTransform.position, ForceMode.Acceleration);
}
The performance issues would most likely be physics issues. Check in the profiler. Running all these physics simulations at once, would most likely be the reason for your drop in performance. You should do as DevDunk suggested, and only simulate physics on cars within view distance or within proximity of your 'player'. @Wenon
Answer by DevDunk · Jan 09, 2021 at 05:24 PM
Don't see any major performance/optimization issues. I recommend you use ECS if you want to use many vehicles. You can also limit the cars rendered and use to those on-screen or within proximity. That would help most